本题要求编写程序,计算N个有理数的平均值。
输入第一行给出正整数N(≤100);第二行中按照a1/b1 a2/b2 …的格式给出N个分数形式的有理数,其中分子和分母全是整形范围内的整数;如果是负数,则负号一定出现在最前面。
在一行中按照a/b的格式输出N个有理数的平均值。注意必须是该有理数的最简分数形式,若分母为1,则只输出分子。
4
1/2 1/6 3/6 -5/10
1/6
2
4/3 2/3
1
#include<iostream>
using namespace std;
#define N 100
struct Rational{
int n;
int d;
};
int gcd(int a, int b)
{
int temp;
if (a == 0 & b == 0)
{
return 0;
}
if (a == 0)
{
return b;
}
if (b == 0)
{
return a;
}
while (1)
{
temp = a%b;
if (temp == 0)
{
return b;
}
a = b;
b = temp;
}
return b;
}
int main(void)
{
struct Rational ra[N],r;
int n;
cin>>n;
for (int i = 0; i < n; i++)
{
scanf("%d/%d", &ra[i].n, &ra[i].d);
}
r.n = 0;
r.d = 1;
for (int i = 0; i < n; i++)
{
r.n = r.n*ra[i].d + r.d*ra[i].n;
r.d = r.d*ra[i].d;
}
r.d *= n; //平均值
int g = gcd(r.n, r.d);
if (g != 0)
{
r.n /= g;
r.d /= g;
}
if (r.d == 1)
{
cout << r.n;
}
else if (r.n == 0)
{
cout << r.n;
}
else
{
cout << r.n << ‘/‘ << r.d;
}
return 0;
}
原文:http://www.cnblogs.com/hhboboy/p/4888505.html