【PAT乙级】1034 有理数四则运算 (20 分)
作者:互联网
#include<cstdio>
#include<iostream>
#include<string>
using namespace std;
long long int a,b,c,d,sum1,sum2;
int gcd(int a,int b)
{
if(b==0) return a;
else return gcd(b,a%b);
}
void print(long long int a,long long int b)
{
long long int s;
double flag; flag=a*1.0/b;
s=a/b;
a=a-s*b;
long long int temp=gcd(a,b);
a=a/temp;
b=b/temp;
if(flag<0)
{
a=abs(a),b=abs(b),s=abs(s);
if(s||a==0)
{
if(a==0) printf("(%d)",s*-1);
else printf("(%d %d/%d)",s*-1,a,b);
}
else printf("(%d/%d)",a*-1,b);
}
else
{
if(s||a==0)
{
if(a==0) printf("%d",s);
else printf("%d %d/%d",s,a,b);
}
else printf("%d/%d",a,b);
}
}
int main(void)
{
scanf("%lld/%lld %lld/%lld",&a,&b,&c,&d);
sum2=b*d/gcd(b,d);
sum1=a*sum2/b+c*sum2/d;
print(a,b); printf(" + "); print(c,d); printf(" = "); print(sum1,sum2); printf("\n");
sum1=a*sum2/b-c*sum2/d;
print(a,b); printf(" - "); print(c,d); printf(" = "); print(sum1,sum2); printf("\n");
sum2=b*d;
sum1=a*c;
print(a,b); printf(" * "); print(c,d); printf(" = "); print(sum1,sum2); printf("\n");
sum1=a*d;
sum2=b*c;
if(c==0)
{
print(a,b); printf(" / "); print(c,d); printf(" = "); printf("Inf"); printf("\n");
}
else
{
print(a,b); printf(" / "); print(c,d); printf(" = "); print(sum1,sum2); printf("\n");
}
return 0;
}
标签:PAT,int,sum2,long,sum1,printf,print,20,1034 来源: https://blog.csdn.net/qq_46527915/article/details/118580316