B1081 Rational Sum (20分)
晓得了,原来gcd是可以处理负数的啊~~
#include<bits/stdc++.h>
#include<cstring>
using namespace std;
const int MAX=110;
int gcd(int a,int b)
{
return !b ? a:gcd(b,a%b);
}
int main()
{
int n;
int a,b;
cin>>n;
scanf("%d/%d",&a,&b);
int t=gcd(a,b);
a/=t,b/=t;
for(int i=1;i<n;i++)
{
int c,d;
scanf("%d/%d",&c,&d);
a=a*d+b*c;
b=b*d;
t=gcd(a,b);
a/=t;
b/=t;
}
if(a%b==0)
printf("%d",a/b);
else
{
if(abs(a)>abs(b))
{
if(a>0)
printf("%d %d/%d",a/b,a%b,b);
else
{
a=-a;
printf("-%d %d/%d",a/b,a%b,b);
}
}
else
printf("%d/%d",a,b);
}
return 0;
}
网友评论