以前在basic做过,那时就知道了把分数显示单独写成函数能减少代码量。通过写函数减少代码量的方法还是应该多学习
#include<cstdio>
typedef long long int LL;
struct node{
LL fenz,fenm;
node(LL a=0,LL b=1):fenz(a),fenm(b){
}
};
LL gcd(LL a,LL b){
if(a<0) a=-a;
if(b==0) return a;
return gcd(b,a%b);
}
void show(const node& a){
LL z=a.fenz;
LL m=a.fenm;
int ok=0;
if(m<0){
m=-m;
z=-z;
}
if(z<0){
z=-z;
ok=1;
}
if(ok) printf("(-");
LL k=z/m;
if(k*m==z) printf("%lld",k);
else{
z%=m;
if(k) printf("%lld ",k);
printf("%lld/%lld",z,m);
}
if(ok) printf(")");
}
void add(const node& a,const node& b){
node t;
show(a);
printf(" + ");
show(b);
printf(" = ");
t.fenz=a.fenz*b.fenm+a.fenm*b.fenz;
t.fenm=a.fenm*b.fenm;
LL k=gcd(t.fenz,t.fenm);
t.fenz/=k;
t.fenm/=k;
show(t);
}
void dec(const node& a,const node& b){
node t;
show(a);
printf(" - ");
show(b);
printf(" = ");
t.fenz=a.fenz*b.fenm-a.fenm*b.fenz;
t.fenm=a.fenm*b.fenm;
LL k=gcd(t.fenz,t.fenm);
t.fenz/=k;
t.fenm/=k;
show(t);
}
void mul(const node& a,const node& b){
node t;
show(a);
printf(" * ");
show(b);
printf(" = ");
t.fenz=a.fenz*b.fenz;
t.fenm=a.fenm*b.fenm;
LL k=gcd(t.fenz,t.fenm);
t.fenz/=k;
t.fenm/=k;
show(t);
}
void div(const node& a,const node& b){
node t;
show(a);
printf(" / ");
show(b);
printf(" = ");
t.fenz=a.fenz*b.fenm;
t.fenm=a.fenm*b.fenz;
LL k=gcd(t.fenz,t.fenm);
t.fenz/=k;
t.fenm/=k;
if(t.fenm) show(t);
else printf("Inf");
}
int main(){
node a,b;
scanf("%lld/%lld %lld/%lld",&a.fenz,&a.fenm,&b.fenz,&b.fenm);
LL k=gcd(a.fenz,a.fenm);
LL t=gcd(b.fenz,b.fenm);
a.fenz/=k;a.fenm/=k;
b.fenz/=t;b.fenm/=t;
add(a,b);putchar('\n');
dec(a,b);putchar('\n');
mul(a,b);putchar('\n');
div(a,b);putchar('\n');
return 0;
}
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/2Sample 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/6Sample 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