标签:style blog http color os io for ar 2014
1 /* 2 * Main.c 3 * F5-结构-05. 有理数均值 4 * Created on: 2014年8月26日 5 * Author: Boomkeeper 6 *********部分通过*浮点错误****** 7 */ 8 9 #include <stdio.h> 10 /** 11 * 有理数结构体 12 */ 13 struct rational { 14 int numerator; 15 int denominator; 16 }; 17 /** 18 * 最大公约数 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; //题目中的N 32 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 //通分求和 47 for (i = 1; i < n; i++) { 48 result.numerator = result.numerator * num[i].denominator 49 + num[i].numerator * result.denominator; 50 result.denominator = result.denominator * num[i].denominator; 51 if (result.numerator != 0) { 52 //避免累加和超出int范围,每次累加后进行约分 53 int gcd = greatCommonDivisor(result.numerator, result.denominator); 54 result.numerator /= gcd; 55 result.denominator /= gcd; 56 } 57 58 } 59 60 //求平均 61 result.denominator *= n; 62 int gcd = greatCommonDivisor(result.numerator, result.denominator); 63 result.numerator /= gcd; 64 result.denominator /= gcd; 65 66 //输出结果 67 if (result.denominator == 1) 68 printf("%d\n", result.numerator); 69 else 70 printf("%d/%d\n", result.numerator, result.denominator); 71 72 return 0; 73 }
题目链接:
http://pat.zju.edu.cn/contests/basic-programming/%E7%BB%93%E6%9E%84-05
标签:style blog http color os io for ar 2014
原文地址:http://www.cnblogs.com/boomkeeper/p/F5.html