本题要求编写程序,计算N个有理数的平均值。
输入格式:
输入第一行给出正整数N(≤100);第二行中按照a1/b1 a2/b2 …的格式给出N个分数形式的有理数,其中分子和分母全是整形范围内的整数;如果是负数,则负号一定出现在最前面。
输出格式:
在一行中按照a/b的格式输出N个有理数的平均值。注意必须是该有理数的最简分数形式,若分母为1,则只输出分子。
#include<stdio.h>
#include <math.h>
#include<string.h>
int main(void)
{
int n, sumA=0, sumB=1, a, b, i, g;
scanf_s("%d", &n);
for (i = 0; i < n; i++) {
scanf_s("%d/%d", &a, &b);
//利用了两分母相乘必然是公倍数的定理
sumA *= b; //前分子*后分母
sumA += a * sumB; //总=前分子+后分子*前分母
sumB *= b; //前分母*后分母(上下同乘) (后分母==前分母,不管)
if (i == n - 1) sumB *= n; //最后求平均,分母*n == 分子*1/n == /n
g = gcd(sumA, sumB); //求最大公约数
sumA /= g; //约分
sumB /= g;
}
if (sumB != 1) printf("%d/%d", sumA, sumB);
else printf("%d", sumA);
return 0;
}
int gcd(int a, int b) //递归求最大公约数
{
if (b==0) return a;
else gcd(b, a % b);
}