1081 Rational Sum
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
分析:对于分数的加法运算,可以设计分数结构体来解决。考虑到输入的格式,因此对负分数不做特殊处理,直接读入其分子即可,如-2/5的分子读入为-2。计算则按照通分-计算-约分的循环过程进行。
需要注意的是分数的输出,同时要考虑0的情况,否则容易出错。另外,在通分计算时可能超出整型范围,因此采用长整型数据。
#include<iostream>
using namespace std;
typedef long long ll;
struct fract {
ll upp;//分子,负分数的负号归入分子
ll sub;//分母,两者的范围都应当是长整型
};
ll gcd(ll a,ll b) {
return b == 0 ? a : gcd(b, a % b);//求最大公约数
}
fract simp(fract f) {
//用于约分和转换带分数
fract simp = f;
ll g;
if (abs(simp.upp) > simp.sub)
g = gcd(abs(simp.upp), simp.sub);
else g = gcd(simp.sub, abs(simp.upp));
simp.upp /= g;
simp.sub /= g;
return simp;
}
int main() {
char c;//用于接收分号
int n;
cin >> n;
fract fracs[101];
for (int i = 0;i < n;i++) {
cin >> fracs[i].upp >> c >> fracs[i].sub;
}
fract res = fracs[0];
for (int i = 1;i < n;i++) {
ll down=res.sub * fracs[i].sub;//使用自乘运算会影响到后续的计算
ll up = res.upp * fracs[i].sub + fracs[i].upp * res.sub;//通分计算
res.sub = down;
res.upp = up;
res = simp(res);//每一步简化一次,减少计算量
}
if (abs(res.upp) < res.sub) {//化为带分数时比较分子和分母的绝对值
if (res.upp == 0)
cout << res.upp << endl;//一定要注意如何处理0的结果
else cout << res.upp<<'/' << res.sub << endl;
}
else if (abs(res.upp) % res.sub == 0) {//整数
cout << res.upp / res. sub << endl;
}
else {
cout << res.upp / res.sub<<" " <<abs(res.upp)%res.sub << '/' << res.sub << endl;//分子要绝对值
}
return 0;
}