文章目录

1 题目

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

2 解析

2.1 题意

输出多个分数的和。

2.2 思路

正常的分数运算。
long long保存值,以防溢出。
使用abs时,用algorithm文件里面的。

3 参考代码

#include 
#include

using std::abs;

typedef long long ll;

struct Fraction{
ll up;
ll down;
}ans,a;

ll gcd(ll a, ll b){
return !b ? a :gcd(b, a%b);
}

Fraction reduction(Fraction res){
if(res.up < 0){
res.up = -res.up;
res.down = -res.down;
}

if(res.up == 0){
res.down = 1;
}else{
ll d = gcd(res.up, res.down);
res.up /= d;
res.down /= d;
}

return res;
}

Fraction add(Fraction f1, Fraction f2){
Fraction res;
res.up = f1.up * f2.down + f2.up * f1.down;
res.down = f1.down * f2.down;
return reduction(res);
}

void showResult(Fraction res){
if(res.down == 1){
printf("%lld", res.up);
}else if(abs(res.up) > res.down){
printf("%lld %lld/%lld", res.up/res.down, abs(res.up)%res.down, res.down);
}else{
printf("%lld/%lld", res.up, res.down);
}
}

int main(int agrc, char const *agrv[]){
int n;
scanf("%d", &n);
scanf("%lld/%lld", &ans.up, &ans.down);
n--;
while(n--){
scanf("%lld/%lld", &a.up, &a.down);
ans = add(ans, a);
}
showResult(ans);
return 0;
}