PAT_A1088#Rational Arithmetic

时间:2023-03-10 06:16:13
PAT_A1088#Rational Arithmetic

Source:

PAT A1088 Rational Arithmetic (20 分)

Description:

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

Keys:

Code:

 /*
Data: 2019-07-05 20:10:35
Problem: PAT_A1088#Rational Arithmetic
AC: 21:04 题目大意:
分数的加减乘除
*/
#include<cstdio>
#include<algorithm>
using namespace std;
struct fr
{
long long up,down;
}s1,s2; long long GCD(long long a, long long b)
{
return !b ? a : GCD(b,a%b);
} fr Reduct(fr r)
{
if(r.down < )
{
r.up = -r.up;
r.down = -r.down;
}
if(r.up==)
r.down=;
else
{
int gcd = GCD(abs(r.up),abs(r.down));
r.up /= gcd;
r.down /= gcd;
}
return r;
} fr Add(fr f1, fr f2)
{
fr r;
r.up = f1.up*f2.down+f1.down*f2.up;
r.down = f1.down*f2.down;
return Reduct(r);
} fr Dif(fr f1, fr f2)
{
fr r;
r.up = f1.up*f2.down-f1.down*f2.up;
r.down = f1.down*f2.down;
return Reduct(r);
} fr Pro(fr f1, fr f2)
{
fr r;
r.up = f1.up*f2.up;
r.down = f1.down*f2.down;
return Reduct(r);
} fr Quo(fr f1, fr f2)
{
fr r;
r.up = f1.up*f2.down;
r.down = f1.down*f2.up;
return Reduct(r);
} void Show(fr r)
{
r = Reduct(r);
if(r.up < )
printf("(");
if(r.down == )
printf("%lld", r.up);
else if(abs(r.up) > r.down)
printf("%lld %lld/%lld", r.up/r.down,abs(r.up)%r.down,r.down);
else
printf("%lld/%lld", r.up,r.down);
if(r.up < )
printf(")");
} int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("Test.txt", "r", stdin);
#endif // ONLINE_JUDGE scanf("%lld/%lld %lld/%lld", &s1.up,&s1.down,&s2.up,&s2.down);
char op[] = {'+','-','*','/'};
for(int i=; i<; i++)
{
Show(s1);printf(" %c ", op[i]);Show(s2);printf(" = ");
if(i==) Show(Add(s1,s2));
else if(i==) Show(Dif(s1,s2));
else if(i==) Show(Pro(s1,s2));
else
{
if(s2.up==) printf("Inf");
else Show(Quo(s1,s2));
}
printf("\n");
} return ;
}