pat求助!! 感激不尽
求助!!!哪位大神帮看看,感激不尽,pat advanced 1088 pat1088题 在本站测试正确 在pat上测试错误!!
#include<iostream>
#include<cstdio>
using namespace std;
long long lcm(long long x,long long y);
long long gcd(long long x,long long y);
void print(long long x,long long y);
int main(){
long a1,b1,a2,b2,g; //g用来存储最大公约数
scanf("%ld/%ld",&a1,&b1);
scanf("%ld/%ld",&a2,&b2);
long long m1=a1,n1=b1,m2=a2,n2=b2;
if(m1!=0){
g=gcd(m1,n1);
m1=m1/g;
n1=n1/g;
}
if(m2!=0){
g=gcd(m2,n2);
m2=m2/g;
n2=n2/g;
}
long long l=lcm(b1,b2); //最小公倍数 --和/差的分母
long long add=(l/b1)*a1+(l/b2)*a2;// 和的分子
long long minus=(l/b1)*a1-(l/b2)*a2; //差的分子
long long l2=l;
if(add!=0){
g=gcd(add,l);
add=add/g;
l=l/g;
}
print(m1,n1);
printf(" + ");
print(m2,n2);
printf(" = ");
print(add,l);
printf("\n");
if(minus!=0){
g=gcd(minus,l2);
minus=minus/g;
l2=l2/g;
}
print(m1,n1);
printf(" - ");
print(m2,n2);
printf(" = ");
print(minus,l2);
printf("\n");
print(m1,n1);
printf(" * ");
print(m2,n2);
printf(" = ");
if(a1!=0&&a2!=0){
long long muz=a1*a2;//积的分子
long long mum=b1*b2;
g=gcd(muz,mum);
muz=muz/g;
mum= mum/g;
print(muz,mum);
printf("\n");
}else{ //积为0
//long long muz=0;//积的分子
printf("0\n");
}
print(m1,n1);
printf(" / ");
print(m2,n2);
printf(" = ");
if(a2==0){ //商为Inf
printf("Inf\n");
}else{
if(a1==0) {
//dez=0;//商为0
printf("0\n");
}
else{
long long dez=a1*b2;//商的分子
long long dem=b1*a2;
g=gcd(dez,dem);
dez=dez/g;
dem= dem/g;
print(dez,dem);
printf("\n");
}
}
return 0;
}
long long lcm(long long x,long long y){
long long i,l1,l2;
long long top=l1*l2;
for(i=1;i<=top;i++){
l1=x*i;
l2=y*i;
if(l1%y==0||l2%x==0)
break;
}
if(l1%y==0) return l1;
else return l2;
}
long long gcd(long long x,long long y){
long long g=1;
x=x>0?x:-x;
y=y>0?y:-y;
long long min=x>y?y:x;
long long i;
for(i=2;i<=min;i++){
while(x%i==0&&y%i==0){
g=g*i;
x=x/i;
y=y/i;
}
min=x>y?y:x;
}
return g;
}
void print(long long x,long long y){
if(x==0) {
printf("0");
return;
}
if(y<0) {
y=-y;
x=-x;
}
if(x>0){
long long integer=x/y;
long long mod=x%y;
if(integer == 0) printf("%lld/%lld",x,y);
else {
if(mod==0) printf("%lld",integer);
else printf("%lld %lld/%lld",integer,mod,y);
}
return;
}
if(x<0){
printf("(");
x=-x;
long long integer=-(x/y);
long long mod=x%y;
if(integer==0) printf("%lld/%lld",-x,y);
else{
if(mod==0) printf("%lld",integer);
else printf("%lld %lld/%lld",integer,mod,y);
}
printf(")");
return;
}
}