标签:
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
思路:一定要注意一些特殊的情况,比如说0输出的时候要注意。
1 #include <iostream> 2 #include <cstdio> 3 using namespace std; 4 #define MAX 110 5 struct element 6 { 7 long long up; 8 long long down; 9 }ele[MAX]; 10 long long GCD(long long a,long long b) 11 { 12 return !b?a:GCD(b,a%b); 13 } 14 15 element Add(element A,element B) 16 { 17 struct element temp; 18 long long down=A.down*B.down; 19 long long up=A.up*B.down+B.up*A.down; 20 long long int d=GCD(up,down); 21 up/=d; 22 down/=d; 23 temp.up=up; 24 temp.down=down; 25 return temp; 26 } 27 void Print(element A) 28 { 29 if(A.up==0) 30 { 31 printf("0\n"); 32 } 33 else if(A.up<A.down) 34 { 35 printf("%lld/%lld\n",A.up,A.down); 36 } 37 else 38 { 39 long long Jia=A.up/A.down; 40 A.up=A.up%A.down; 41 if(A.up!=0) 42 printf("%lld %lld/%lld\n",Jia,A.up,A.down); 43 else 44 printf("%lld\n",Jia); 45 } 46 } 47 int main(int argc, char *argv[]) 48 { 49 int N; 50 scanf("%d",&N); 51 element sum; 52 sum.up=0; 53 sum.down=0; 54 for(int i=0;i<N;i++) 55 { 56 if(i==0) 57 { 58 scanf("%lld/%lld",&ele[i].up,&ele[i].down); 59 sum.up=ele[i].up; 60 sum.down=ele[i].down; 61 continue; 62 } 63 scanf("%lld/%lld",&ele[i].up,&ele[i].down); 64 sum=Add(sum,ele[i]); 65 } 66 Print(sum); 67 return 0; 68 }
标签:
原文地址:http://www.cnblogs.com/GoFly/p/4296582.html