1088 Rational Arithmetic (20分)(模拟)

1088 Rational Arithmetic (20分)
 

For two rational numbers, your task is to implement the basic arithmetics, that is, to calculate their sum, difference, product and quotient.

Input Specification:

Each input file contains one test case, which gives in one line the two rational numbers in the format a1/b1 a2/b2. The numerators and the denominators are all in the range of long int. If there is a negative sign, it must appear only in front of the numerator. The denominators are guaranteed to be non-zero numbers.

Output Specification:

For each test case, print in 4 lines the sum, difference, product and quotient of the two rational numbers, respectively. The format of each line is number1 operator number2 = result. Notice that all the rational numbers must be in their simplest form k a/b, where k is the integer part, and a/b is the simplest fraction part. If the number is negative, it must be included in a pair of parentheses. If the denominator in the division is zero, output Inf as the result. It is guaranteed that all the output integers are in the range of long int.

Sample Input 1:

2/3 -4/2
 

Sample Output 1:

2/3 + (-2) = (-1 1/3)
2/3 - (-2) = 2 2/3
2/3 * (-2) = (-1 1/3)
2/3 / (-2) = (-1/3)
 

Sample Input 2:

5/3 0/6
 

Sample Output 2:

1 2/3 + 0 = 1 2/3
1 2/3 - 0 = 1 2/3
1 2/3 * 0 = 0
1 2/3 / 0 = Inf
 
这题,一开始我写了四个计算函数,写完发现完全可以用一个代替,最后还写了一个输出函数,后来发现所有函数都可以整合在一起。但是有一个点没搞懂的就是,大家都是取绝对值,记录结果正负,为什么我就样例2老是WA呢,于是,学了一下柳神的代码,不错牛皮。
 
 1 #include <cstdio>
 2 #include <cmath>
 3 using namespace std;
 4 
 5 typedef long long ll;
 6 ll gcd(ll a, ll b) {
 7     return b == 0 ? a : gcd(b, a % b);
 8 }
 9 
10 void func(ll m, ll n) {
11     if(m * n == 0) {
12         printf("%s", n == 0 ? "Inf" : "0");
13         return;
14     }
15     bool flag = ((m < 0 && n > 0) || (m > 0 && n < 0));
16     m = abs(m), n = abs(n);
17     ll x = m / n;
18     printf("%s", flag ? "(-" : "");
19     if(x) printf("%lld", x);
20     if(!(m % n)) {
21         if(flag) printf(")");
22         return;
23     }
24     if(x) printf(" ");
25     m = m % n;
26     ll t = gcd(m, n);
27     m /= t, n /= t;
28     printf("%lld/%lld%s", m, n, flag ? ")" : "");
29 }
30 
31 int main() {
32     ll a, b, c, d;
33     scanf("%lld/%lld %lld/%lld", &a, &b, &c, &d);
34     func(a, b); printf(" + "); func(c, d); printf(" = "); func(a * d + b * c, b * d); printf("\n");
35     func(a, b); printf(" - "); func(c, d); printf(" = "); func(a * d - b * c, b * d); printf("\n");
36     func(a, b); printf(" * "); func(c, d); printf(" = "); func(a * c, b * d); printf("\n");\
37     func(a, b); printf(" / "); func(c, d); printf(" = "); func(a * d, b * c);
38     return 0;
39 }

再贴一下,我wa样例2的代码,不过后来这个代码被我改ac了。问题在哪呢?

抱歉是我自己羊癫疯发作了,真的垃圾哦,代码能力太差了。

真就恐怖。

 1 printa(a1, b1); 2 printf(" + "); 3 printa(a2, b2); 

这a和b我都没有化简.....

猜你喜欢

转载自www.cnblogs.com/bianjunting/p/13170492.html