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
, wherek
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
code
#include <iostream>
using namespace std;
long long findcom(long long t1, long long t2) {
return t2 == 0 ? abs(t1) : findcom(t2, t1 % t2);
}
void putration(long long a, long long b)
{
if(a==0) {
cout << 0;
} else {
if(b==0) {
cout << "Inf";
} else {
if(b<0) {a=-a;b=-b;}
long long c;
c = findcom(a,b);
a = a/c; b = b/c;
long long in;
in = a/b;
a = a%b;
if(a==0) {
if(in<0) {
printf("(%lld)",in);
} else {
printf("%lld",in);
}
} else if(a>0) {
if(in==0) {
printf("%lld/%lld",a,b);
} else {
printf("%lld %lld/%lld",in,a,b);
}
} else{
if(in==0) {
printf("(%lld/%lld)",a,b);
} else {
printf("(%lld %lld/%lld)",in,abs(a),b);
}
}
}
}
}
int main()
{
long long nu1,de1,nu2,de2;
long long nu3,de3;
long long com;
scanf("%lld/%lld %lld/%lld",&nu1,&de1,&nu2,&de2);
// addition
putration(nu1,de1);
printf(" + ");
putration(nu2,de2);
printf(" = ");
nu3 = nu1*de2 + nu2*de1;
de3 = de1*de2;
putration(nu3,de3);
printf("\n");
// subtraction
putration(nu1,de1);
printf(" - ");
putration(nu2,de2);
printf(" = ");
nu3 = nu1*de2 - nu2*de1;
de3 = de1*de2;
putration(nu3,de3);
printf("\n");
// time
putration(nu1,de1);
printf(" * ");
putration(nu2,de2);
printf(" = ");
com = findcom(nu1,nu2);
nu3 = nu1*nu2;
de3 = de1*de2;
putration(nu3,de3);
printf("\n");
// division
putration(nu1,de1);
printf(" / ");
putration(nu2,de2);
printf(" = ");
com = findcom(nu1,nu2);
nu3 = nu1*de2;
de3 = nu2*de1;
putration(nu3,de3);
printf("\n");
}
note
- 忘记考虑除法可能会导致分母出现负数,导致一直一个测试点不通过
- 辗转相除求最大公约数的方法应该记下来
- 细心啊细心
网友评论