题目链接
题目分析
求N
个分数之和
解题思路
按分数计算规则 做就行!
AC程序(C++)
/**********************************
*@ID: 3stone
*@ACM: PAT.A1081 Rational Sum
*@Time: 17/2/27
*@IDE: DEV C++
***********************************/
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
const int maxn = 110;
struct Fraction {
int up, down;
}frac[maxn];
//最大公约数
int gcd(int a, int b) {
if(a < b) swap(a, b);
if(b == 0) return a;
else return gcd(b, a % b);
}
//化简整理分数
Fraction reduction(Fraction f) {
if(f.down < 0) {
f.up = -f.up;
f.down = -f.down;
}
if(f.up == 0) f.down = 1;
else {
int d = gcd(abs(f.up), abs(f.down)); //若是整数的话,此处就把down化为1了
f.up /= d;
f.down /= d;
}
return f;
}
//分数加法
Fraction add(Fraction a, Fraction b) {
a.up = a.up * b.down + b.up * a.down;
a.down = a.down * b.down;
return reduction(a);
}
//输出分数结果
void showResult(Fraction a) {
if(a.down == 1) printf("%d", a.up); //整数
else if(abs(a.up) > a.down) { //假分数
printf("%d %d/%d", a.up / a.down, abs(a.up) % a.down, a.down);
} else { //真分数
printf("%d/%d", a.up, a.down);
}
}
int main() {
int n;
Fraction sum, temp;
sum.up = 0; sum.down = 1;
scanf("%d", &n); //求n个分数的和
for(int i = 0; i < n; i++) {
scanf("%d/%d", &temp.up, &temp.down);
sum = reduction(add(sum, reduction(temp)));
}
showResult(sum);
printf("\n");
return 0;
}