PAT-A-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:

1
2
5
2/5 4/15 1/30 -2/60 8/3

Sample Output 1:

1
3 1/3

Sample Input 2:

1
2
2
4/3 2/3

Sample Output 2:

1
2

Sample Input 3:

1
2
3
1/3 -1/6 1/8

Sample Output 3:

1
7/24

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
using namespace std;

typedef long long ll;

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

struct Fraction{
ll up,down;//分子和分母
};
//化简
void reduction(Fraction& f1){
//正负的化简
if(f1.down<0){
f1.up=-f1.up;
f1.down=-f1.down;
}
//为0的化简
if(f1.up==0)
f1.down=1;
else{
//约去公约数
ll d = gcd(abs(f1.up),abs(f1.down));
f1.up/=d;
f1.down/=d;
}
}

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

void showFraction(Fraction& f1){
if(f1.down==1)
printf("%lld\n",f1.up);
else if(abs(f1.up)>f1.down)//假分式
printf("%lld %lld/%lld\n",f1.up/f1.down,abs(f1.up)%f1.down,f1.down);
else
printf("%lld/%lld\n",f1.up,f1.down);

}

int main(){
int n;
scanf("%d",&n);
Fraction sum,temp;
sum.up=0,sum.down=1;

while(n--){
scanf("%lld/%lld",&temp.up,&temp.down);
add(sum,temp);
}

showFraction(sum);
return 0;
}

----\(˙<>˙)/----赞赏一下吧~