题目描述
John最近对分数很感兴趣,在研究分数的加减运算。现在要求计算两个分数的运算。
输入描述:
输入一个正整数T,表示有T组数据
每组数据包括5个整数op,a,b,c,d
op为1表示a/b + c/d;op为0表示为a/b – c/d
其中1 <= T, a,b,c,d <= 100;
输出描述:
输出分数运算结果“x/y”,要求x/y是最简分数。
输入
4
1 1 2 1 3
0 1 2 1 2
1 1 2 1 2
0 1 3 1 2
输出
5/6
0/1
1/1
-1/6
备注:
如果有运算符,应在x前面,如“-1/6”,而不是“1/-6”。
#include<iostream>
#include<cmath>
using namespace std;
int gcd(int m, int n)
{
while(m>0)
{
int c = n % m;
n = m;
m = c;
}
return n;
}
int main()
{
int t,op,a,b,c,d,s,s1,x;
cin>>t;
while(t--)
{
cin>>op>>a>>b>>c>>d;
if(op==1)
{
s=(a*d+b*c);
s1=b*d;
if(s!=0)
{
x=gcd(s,s1);
cout<<s/x<<"/"<<s1/x<<endl;
}
else
{
cout<<0<<"/"<<1<<endl;
}
}
else
{
s=abs(a*d-b*c);
s1=b*d;
if(s!=0)
{
x=gcd(s,s1);
if((a*d-b*c)<0)
cout<<"-"<<s/x<<"/"<<s1/x<<endl;
else
cout<<s/x<<"/"<<s1/x<<endl;
}
else
{
cout<<0<<"/"<<1<<endl;
}
}
}
}