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
思路
这题大体的思路比较简单,但是细节上的东西要注意的地方有很多。题目大意就是给你几个分数,让你计算这几个分数的和,如果是假分数,要输出带分数的形式。
下面讲一下这题的【注意点】:
- 因为给出的分数不一定是最简的(比如样例1的-2/60),因此,需要得到这个分数之后就对它进行化简,然后存入input数组里面;
- 化简的时候求分子分母的最大公约数需要取绝对值,即:gcd(abs(), abs()),而且化简函数里也要特判分子为0的情况;
- 为了防止经过乘法之后超出int型范围,分子分母最好采用long long型存储;
- 如果是假分数的形式,要输出带分数,即:整数+真分数,当真分数的分子为0时,不输出这个真分数,只输出一个整数;
- 同理,如果本就是真分数的形式,当真分数的分子为0时,这时只要输出0即可(不要输出0/1,这是最后一个测试点考察的内容)。
代码
#include<cstdio>
#include<stdlib.h>
#include<algorithm>
#include<vector>
#include<string.h>
#include<iostream>
using namespace std;
struct Fraction{
long long up, down;
};
vector<Fraction> input;
int gcd(int a, int b){
if(b==0) return a;
else return gcd(b, a%b);
}
Fraction huajian(Fraction a){
if(a.up==0){
a.down = 1;
}
else{
int yueshu = gcd(abs(a.up), abs(a.down));
a.up /= yueshu;
a.down /= yueshu;
}
return a;
}
Fraction add(Fraction a, Fraction b){
Fraction c;
c.up = a.up*b.down+b.up*a.down;
c.down = a.down*b.down;
return c;
}
int main()
{
int N;
cin>>N;
for(int i=0;i<N;i++){
string temp;
cin>>temp;
int pos = temp.find("/");
string fenzi = temp.substr(0,pos);
string fenmu = temp.substr(pos+1);
Fraction tmp;
tmp.up = stoll(fenzi);
tmp.down = stoll(fenmu);
tmp = huajian(tmp);
input.push_back(tmp);
}
Fraction result;
result.up = 0;
result.down = 1;
for(int i=0;i<input.size();i++){
result = add(result, input[i]);
}
result = huajian(result);
if(result.up>=result.down){//假分数
if(abs(result.up)%result.down==0){
cout<<result.up/result.down;//只有整数
}
else{
cout<<result.up/result.down<<" "<<abs(result.up)%result.down<<"/"<<result.down;
//带分数
}
}
else{//真分数
if(result.up==0) cout<<"0";
else cout<<result.up<<"/"<<result.down;
}
return 0;
}