简单题。
注意:读入的分数可能不是最简的。输出时也需要转换成最简。
#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<map>
#include<stack>
#include<queue>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std; struct FS
{
long long fz,fm;
FS(long long a,long long b)
{
fz=a;
fm=b;
}
}; long long gcd(long long a,long long b)
{
if(b==) return a;
return gcd(b,a%b);
} FS change(FS res)
{
if(res.fz!=)
{
long long GCD=gcd(abs(res.fz),abs(res.fm));
res.fz=res.fz/GCD;
res.fm=res.fm/GCD;
} else
{
res.fz=;
res.fm=;
} return res;
} FS ADD(FS a,FS b)
{
FS res(,); res.fz=a.fz*b.fm+b.fz*a.fm;
res.fm=a.fm*b.fm; res=change(res);
return res;
} FS SUB(FS a,FS b)
{
FS res(,); res.fz=a.fz*b.fm-b.fz*a.fm;
res.fm=a.fm*b.fm; res=change(res);
return res;
} FS MUL(FS a,FS b)
{
FS res(,); res.fz=a.fz*b.fz;
res.fm=a.fm*b.fm; res=change(res);
return res;
} FS DIV(FS a,FS b)
{
FS res(,); if(b.fz==)
{
res.fz=;
res.fm=;
return res;
} if(a.fz==) return res; res.fz=a.fz*b.fm;
res.fm=a.fm*b.fz; if(res.fm<)
{
res.fm=-res.fm;
res.fz=-res.fz;
} res=change(res);
return res;
} void output(FS a)
{
if(a.fm==)
{
printf("Inf");
return;
} if(a.fz==)
{
printf("");
return;
} a=change(a);
if(abs(a.fz)<a.fm)
{
if(a.fz<) printf("("); printf("%lld/%lld",a.fz,a.fm);
if(a.fz<) printf(")");
return;
} if(a.fz>)
{
if(a.fz%a.fm==)
{
printf("%lld",a.fz/a.fm);
return;
}
else
{
printf("%lld %lld/%lld",a.fz/a.fm,a.fz%a.fm,a.fm);
return;
}
} else
{
a.fz=-a.fz; printf("(");
if(a.fz%a.fm==)
{
printf("-%lld",a.fz/a.fm);
printf(")");
return;
}
else
{
printf("-%lld %lld/%lld",a.fz/a.fm,a.fz%a.fm,a.fm);
printf(")");
return;
} }
} int main()
{
long long s1,s2,s3,s4;
scanf("%lld/%lld %lld/%lld",&s1,&s2,&s3,&s4); FS a(s1,s2);
FS b(s3,s4); output(a); cout<<" + "; output(b); cout<<" = "; output(ADD(a,b));
cout<<endl;
output(a); cout<<" - "; output(b); cout<<" = "; output(SUB(a,b));
cout<<endl;
output(a); cout<<" * "; output(b); cout<<" = "; output(MUL(a,b));
cout<<endl;
output(a); cout<<" / "; output(b); cout<<" = "; output(DIV(a,b));
cout<<endl; return ;
}