#include<stdio.h>
long abs(long a){
return (a>=0)?a:-a;
}
long gcd(long x,long y){
long t;
while(y){
t=x%y;
x=y;
y=t;
}
return x;
}
void print_num(long a,long b){
if(b==0){
printf("Inf");
}
else if(a==0){
putchar('0');
}
else if((a>0 && b>0)||(a<0 && b<0)){
a=abs(a);
b=abs(b);
if(a%b==0){
printf("%ld",a/b);
}
else if(a>b){
printf("%ld %ld/%ld",a/b,a%b,b);
}
else if(a<b){
printf("%ld/%ld",a,b);
}
}
else if((a>0 && b<0)||(a<0 && b>0)){
a=abs(a);
b=abs(b);
if(a%b==0){
printf("(-%ld)",a/b);
}
else if(a>b){
printf("(-%ld %ld/%ld)",a/b,a%b,b);
}
else if(a<b){
printf("(-%ld/%ld)",a,b);
}
}
}
void print_eq(long a1,long b1,long a2,long b2,long a3,long b3,char ch){
print_num(a1,b1);
printf(" %c ",ch);
print_num(a2,b2);
printf(" = ");
print_num(a3,b3);
putchar('\n');
}
int main(){
long a1,b1,a2,b2;
scanf("%ld/%ld %ld/%ld",&a1,&b1,&a2,&b2);
long a3,b3,tmp;
tmp=gcd(abs(a1),abs(b1));
if(tmp){
a1/=tmp;
b1/=tmp;
}
tmp=gcd(abs(a2),abs(b2));
if(tmp){
a2/=tmp;
b2/=tmp;
}
a3=a1*b2+a2*b1;
b3=b1*b2;
tmp=gcd(abs(a3),abs(b3));
if(tmp){
a3/=tmp;
b3/=tmp;
}
print_eq(a1,b1,a2,b2,a3,b3,'+');
a3=a1*b2-a2*b1;
b3=b1*b2;
tmp=gcd(abs(a3),abs(b3));
if(tmp){
a3/=tmp;
b3/=tmp;
}
print_eq(a1,b1,a2,b2,a3,b3,'-');
a3=a1*a2;
b3=b1*b2;
tmp=gcd(abs(a3),abs(b3));
if(tmp){
a3/=tmp;
b3/=tmp;
}
print_eq(a1,b1,a2,b2,a3,b3,'*');
a3=a1*b2;
b3=b1*a2;
tmp=gcd(abs(a3),abs(b3));
if(tmp){
a3/=tmp;
b3/=tmp;
}
print_eq(a1,b1,a2,b2,a3,b3,'/');
return 0;
}
PAT(Basic Level)_1034_有理数四则运算
最新推荐文章于 2019-09-01 21:18:43 发布