1081 Rational Sum (20 分)
Given N rational numbers in the form numerator/denominator
, you are supposed to calculate their sum.
Input Specification:
Each input file contains one test case. Each case starts with a positive integer N (≤100), followed in the next line N rational numbers a1/b1 a2/b2 ...
where all the numerators and denominators are in the range of long int. If there is a negative number, then the sign must appear in front of the numerator.
Output Specification:
For each test case, output the sum in the simplest form integer numerator/denominator
where integer
is the integer part of the sum, numerator
<denominator
, and the numerator and the denominator have no common factor. You must output only the fractional part if the integer part is 0.
Sample Input 1:
5
2/5 4/15 1/30 -2/60 8/3
Sample Output 1:
3 1/3
Sample Input 2:
2
4/3 2/3
Sample Output 2:
2
Sample Input 3:
3
1/3 -1/6 1/8
Sample Output 3:
7/24
题目要求
给出n个分数,输出他们累加后的结果化简后的值
解题思路
化简:
如果分母<0,先把分母的负号移到分子
如果分子为0,分母=1 这个是为了0/0等于0而不是无效
然后找分子和分母的最大公约数并约去,找最大公约数用辗转相除法
然后就是分数的加法
分子1/分母1 + 分子2/分母2 = (分子1*分母2+分子2*分母1)/分子*分母
完整代码
#include<bits/stdc++.h>
using namespace std;
struct Fraction{
int up,down;
};
int gcd(int a,int b){
if(b==0) return a;
else return gcd(b,a%b);
}
Fraction reduct(Fraction fra){
int d;
if(fra.down<0){
fra.up=-fra.up;
fra.down=-fra.down;
}
if(fra.up==0) fra.down=1;
if(fra.up>=fra.down) d=gcd(abs(fra.up),abs(fra.down));
else d=gcd(abs(fra.down),abs(fra.up));
fra.down/=d;
fra.up/=d;
return fra;
}
Fraction add(Fraction f1,Fraction f2){
Fraction f3;
f3.up=f1.up*f2.down+f2.up*f1.down;
f3.down=f1.down*f2.down;
return reduct(f3);
}
int main(){
int n,i,flag=0;
Fraction result,temp;
result.down=1;
result.up=0;
scanf("%d",&n);
for(i=1;i<=n;i++){
scanf("%d/%d",&temp.up,&temp.down);
result=add(result,temp);
}
if(result.up==0){
printf("0");
}else{
if(abs(result.up)>result.down) {
printf("%d",result.up/result.down);
if(abs(result.up)%result.down!=0){
printf(" %d/%d",abs(result.up)%result.down,result.down);
}
}else{
printf("%d/%d",result.up,result.down);
}
}
return 0;
}