题目名称:
《C/C++/Java/Pascal 程序设计基础》习题集
结构-05. 有理数均值(20)
1 #include <cstdio> 2 3 int gcd(int p,int q) 4 { 5 if(q==0) 6 return p; 7 int r = p%q; 8 return gcd(q,r); 9 } 10 11 int main() 12 { 13 int n,a,b,com; 14 scanf("%d",&n); 15 int up=1,dn=1;//分子分母初始化为1/1 16 for(int i=0;i<n;i++){ 17 scanf("%d/%d",&a,&b); 18 up = b*up+a*dn; 19 dn = b*dn; 20 } 21 up -= dn; 22 up /= n; 23 //小心浮点溢出! 24 if(up==0){ 25 printf("0\n"); 26 return 0; 27 } 28 //分子分母最简化 29 com = gcd(up,dn); 30 up /= com; 31 dn /= com; 32 if(dn==1) 33 printf("%d\n",up); 34 else 35 printf("%d/%d\n",up,dn); 36 return 0; 37 }