0
点赞
收藏
分享

微信扫一扫

PAT (Basic Level) Practice (中文)- 1034 有理数四则运算(20 分)


题目链接:​​点击打开链接​​

题目大意:略。

解题思路:

1、sprintf 妙用,省了很多次的判断。

2、中间过程可能会 long long。

AC 代码

#include<bits/stdc++.h>
#include<cmath>

#define mem(a,b) memset(a,b,sizeof a);
#define INF 0x3f3f3f3f

using namespace std;

typedef long long ll;

string s1,s2,s3;
char c[100];
stringstream ss;
ll a3,b3,a4,b4,a5,b5,t,tt,k;

ll gcd(ll a,ll b){ a=a<0?-a:a; b=b<0?-b:b; return a==0?b:gcd(b%a,a); }

string fun(ll a,ll b)
{
string s;
k=0;
ss.clear(); ss.str("");
if(abs(a)>=b)
{
if(b==1)
{
k=a;
ss<<k; ss>>c;
}
else
{
k=a/b, a=abs(k*b-a);
sprintf(c,"%lld %lld/%lld",k,a,b);
}
}
else
{
if(a==0) c[0]='0',c[1]='\0';
else sprintf(c,"%lld/%lld",a,b);
}

s=c;
if(k<0 || a<0) s="("+s+")";

return s;
}

int main()
{
ll a1,b1,a2,b2;
while(~scanf("%lld/%lld%lld/%lld",&a1,&b1,&a2,&b2))
{
t=gcd(a1,b1);
a1/=t, b1/=t;
t=gcd(a2,b2);
a2/=t, b2/=t;
a3=a1, b3=b1, a4=a2, b4=b2;
s1=fun(a3,b3); s2=fun(a4,b4);

t=b1*b2/gcd(b1,b2);
a1*=t/b1, a2*=t/b2;
// 以上全是公共的

a5=a1+a2, b5=t;
tt=gcd(a5,b5);
a5/=tt, b5/=tt;
s3=fun(a5,b5);
printf("%s %c %s = %s\n",s1.c_str(),'+',s2.c_str(),s3.c_str());

a5=a1-a2, b5=t;
tt=gcd(a5,b5);
a5/=tt, b5/=tt;
s3=fun(a5,b5);
printf("%s %c %s = %s\n",s1.c_str(),'-',s2.c_str(),s3.c_str());

a5=a3*a4, b5=b3*b4;
tt=gcd(a5,b5);
a5/=tt, b5/=tt;
s3=fun(a5,b5);
printf("%s %c %s = %s\n",s1.c_str(),'*',s2.c_str(),s3.c_str());

if(a4==0) printf("%s %c %s = Inf\n",s1.c_str(),'/',s2.c_str());
else
{
a5=abs(a3)*b4, b5=abs(a4)*b3;
tt=gcd(a5,b5);
a5/=tt, b5/=tt;
if(a3*a4>=0) s3=fun(a5,b5);
else s3=fun(-a5,b5);
printf("%s %c %s = %s\n",s1.c_str(),'/',s2.c_str(),s3.c_str());
}
}

return 0;
}


举报

相关推荐

0 条评论