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 |
注意化简……
代码如下:
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 61 62 63 64 65 66 |
#include<stdio.h> typedef struct rational_ { int numerator; int denominator; } rational; void simplify(rational *a) { int i,sign=1; if(a->numerator<0) { sign=-1; a->numerator=-a->numerator; } for(i=2;i<=a->numerator;i++) { if(a->numerator%i==0&&a->denominator%i==0) { a->numerator/=i; a->denominator/=i; i=2; } } a->numerator*=sign; } void add(rational *a,rational *b) { a->numerator*=b->denominator; b->numerator*=a->denominator; a->numerator+=b->numerator; a->denominator*=b->denominator; simplify(a); } void print(rational *a) { if(a->denominator==1||a->numerator==0) { printf("%d\n",a->numerator); } else if(a->numerator>a->denominator||-a->numerator>a->denominator) { printf("%d ",a->numerator/a->denominator); a->numerator%=a->denominator; simplify(a); printf("%d/%d\n",a->numerator,a->denominator); } else { printf("%d/%d\n",a->numerator,a->denominator); } } int main() { int i,n; rational temp,sum; sum.numerator=0; sum.denominator=1; scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d/%d",&(temp.numerator),&(temp.denominator)); simplify(&temp); add(&sum,&temp); } print(&sum); } |