题目链接

时间:2019-09-26 14:23来源:快三平台下载编程
1 /* 2 * Main.c 3 * F5-结构-05. 有理数均值 4 * Created on: 2014年8月26日 5 * Author: Boomkeeper 6 *********部分通过*浮点错误****** 7 */ 8 9 #include stdio.h10 /**11 * 有理数结构体12 */13 struct rational {14 int numer
 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; //题目中的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     //通分求和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             //避免累加和超出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("%dn", result.numerator);69     else70         printf("%d/%dn", result.numerator, result.denominator);71 72     return 0;73 }

图片 1

题目链接:

编辑:快三平台下载编程 本文来源:题目链接

关键词: