1/* 2 * Main. C 3 * F5-structure-05. rational Number Average 4 * created on: August 26, 2014 5 * Author: in the boomkeeper 6 ********** part, the ** floating point error ******* 7 */8 9 # include <stdio. h> 10/** 11 * rational number struct 12 */13 struct rational {14 int numerator; 15 int denominator; 16 }; 17/** 18 * maximum common approx. 19 */20 int greatcommondivisor (int m, int N) {21 int I; 22 for (I = (M <n? M: N); I> 1; I --) {23 if (M % I = 0 & N % I = 0) 24 break; 25} 26 return I; 27} 28 29 int main (void) {30 31 int N; // n32 struct rational num [101]; 33 struct rational result; 34 int I; 35 36 scanf ("% d", & N); 37 getchar (); 38 39 for (I = 0; I <n; I ++) {40 scanf ("% d/% d", & num [I]. numerator, & num [I]. denominator); 41} 42 43 result. numerator = num [0]. numerator; 44 result. denominator = num [0]. denominator; 45 46 // sum of points 47 for (I = 1; I <n; I ++) {48 result. numerator = result. numerator * num [I]. denominator49 + num [I]. numerator * result. denominator; 50 result. denominator = result. denominator * num [I]. denominator; 51 if (result. numerator! = 0) {52 // avoid accumulating and exceeding the int range. After each accumulation, divide about 53 int GCD = greatcommondivisor (result. numerator, result. denominator); 54 result. numerator/= GCD; 55 result. denominator/= GCD; 56} 57 58} 59 60 // calculate the average 61 result. denominator * = N; 62 int GCD = greatcommondivisor (result. numerator, result. denominator); 63 result. numerator/= GCD; 64 result. denominator/= GCD; 65 66 // output result 67 If (result. denominator = 1) 68 printf ("% d \ n", result. numerator); 69 else70 printf ("% d/% d \ n", result. numerator, result. denominator); 71 72 return 0; 73}
Question link:
Http://pat.zju.edu.cn/contests/basic-programming/%E7%BB%93%E6%9E%84-05
* Structure-05. rational number mean