题目描述
Given N rational numbers in the form "numerator/denominator", you are supposed to calculate their sum.
输入描述:
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.
输出描述:
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.
输入例子:
5 2/5 4/15 1/30 -2/60 8/3
输出例子:
3 1/3
1 #include <iostream> 2 #include <vector> 3 #include <math.h> 4 5 using namespace std; 6 7 long int gcd(long int a, long int b) 8 { 9 if(b==0) return a; 10 else return gcd(b,a%b); 11 } 12 13 int main() 14 { 15 double N; 16 cin>>N; 17 long int Inter = 0;//整数 18 long int resa = 0;//答案分子 19 long int resb = 1;//答案分母 20 21 for(int i=0;i<N;++i) 22 { 23 long int a = 0;//输入分子 24 long int b = 0;//输入分母 25 char c; 26 cin >> a >> c >> b; 27 28 int f = 1; 29 if(a<0) 30 { 31 a = a*-1; 32 f = -1; 33 } 34 Inter += a/b; //简化 35 a = a-b*(a/b); 36 37 long int Div = 0;//最大公约数 38 long int Mul = 0;//最小公倍数 39 //化简输入的分数 40 Div = gcd(b,a); 41 a = a/Div; 42 b = b/Div; 43 44 //求最大公倍数 45 if(resb > b) 46 { 47 Div = gcd(resb,b); 48 Mul = resb / Div * b; 49 } 50 else 51 { 52 Div = gcd(b, resb); 53 Mul = b / Div * resb; 54 } 55 //相加 56 resa = resa * (Mul/resb) + f * a * (Mul/b); 57 resb = Mul; 58 //化简有理数 59 Inter += resa / resb; 60 resa = resa - (resa / resb)*resb; 61 62 //化简最简分数 63 Div = gcd(resb, fabs(resa)); 64 resa = resa/Div; 65 resb = resb/Div; 66 } 67 if(Inter==0 && resa==0) 68 cout << 0 << endl; 69 else if(Inter != 0 && resa == 0) 70 cout << Inter << endl; 71 else if(Inter == 0 && resa != 0 ) 72 cout << resa << "/" << resb << endl; 73 else 74 cout << Inter << " " << resa << "/" << resb << endl; 75 76 return 0; 77 }