分析:分数的四则运算,模拟是最烦的,注意负号一直在分子位置处,输出负的假分数时,分子不用输出负号。
#include<stdio.h>
typedef long long ll;
ll abs(ll a){
if(a < 0) return -a;
return a;
}
ll gcd(ll a, ll b){
if(b == 0) return a;
return gcd(b, a%b);
}
void simplify(ll &a, ll &b){
if(a == 0 || b == 0) return ;
ll gcd1 = gcd(a, b);
a /= gcd1;
b /= gcd1;
if(b < 0) {
b = -b;
a = -a;
}
}
void printab(ll a1, ll b1){
if(a1 < 0) printf("(");
if(b1 == 1 || a1 == 0) printf("%lld", a1);
else {
if(a1/b1 == 0) printf("%lld/%lld", a1, b1);
else printf("%lld %lld/%lld", a1/b1, abs(a1)%b1, b1);
}
if(a1 < 0) printf(")");
}
void show(ll a1, ll b1, ll a2, ll b2, ll resa, ll resb, char ch, int flag){
simplify(a1, b1);
simplify(a2, b2);
simplify(resa, resb);
printab(a1, b1);
printf(" %c ", ch);
printab(a2, b2);
printf(" = ");
if(flag) {
printf("Inf\n");
return ;
}
printab(resa, resb);
printf("\n");
}
void plus(ll a1, ll b1, ll a2, ll b2){
ll resa, resb;
resa = a1*b2+a2*b1;
resb = b1*b2;
show(a1, b1, a2, b2, resa, resb, '+', 0);
}
void sub(ll a1, ll b1, ll a2, ll b2){
ll resa, resb;
resa = a1*b2-a2*b1;
resb = b1*b2;
show(a1, b1, a2, b2, resa, resb, '-', 0);
}
void product(ll a1, ll b1, ll a2, ll b2){
ll resa, resb;
resa = a1*a2;
resb = b1*b2;
show(a1, b1, a2, b2, resa, resb, '*', 0);
}
void div(ll a1, ll b1, ll a2, ll b2){
ll resa, resb, gcd1;
resa = a1*b2;
resb = b1*a2;
if(resb == 0) show(a1, b1, a2, b2, resa, resb, '/', 1);
else {
show(a1, b1, a2, b2, resa, resb, '/', 0);
}
}
int main(){
//freopen("in.txt", "r", stdin);
ll a1, a2, b1, b2, gcd1, gcd2;
scanf("%lld/%lld %lld/%lld", &a1, &b1, &a2, &b2);
plus(a1, b1, a2, b2);
sub(a1, b1, a2, b2);
product(a1, b1, a2, b2);
div(a1, b1, a2, b2);
}