PAT甲级——A1081 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 (≤), 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 #include <iostream>
 2 #include <vector>
 3 #include <math.h>
 4 using namespace std;
 5 long int  gcd(long int a, long int b)
 6 {
 7     if(b==0) return a;
 8     else return gcd(b,a%b);    
 9 }
10 int main()
11 {
12     int N;
13     cin >> N;
14     long long Inter = 0, resa = 0, resb = 1, a, b, Div, Mul;
15     for (int i = 0; i < N; ++i)
16     {
17         char c;
18         cin >> a >> c >> b;
19         resa = resa * b + a * resb;//同分相加的分子
20         resb = resb * b;
21         Inter += resa / resb;//简化
22         resa = resa - resb * (resa / resb);
23         Div = gcd(resb, resa);
24         resa /= Div;
25         resb /= Div;
26     }
27     if (Inter == 0 && resa == 0)
28         cout << 0 << endl;
29     else if (Inter != 0 && resa == 0)
30         cout << Inter << endl;
31     else if (Inter == 0 && resa != 0)
32         cout << resa << "/" << resb << endl;
33     else
34         cout << Inter << " " << resa << "/" << resb << endl;
35     return 0;
36 }
原文地址:https://www.cnblogs.com/zzw1024/p/11326646.html