本题要求编写程序,计算N个有理数的平均值。
输入格式:
输入第一行给出正整数N(≤100);第二行中按照a1/b1 a2/b2 …
的格式给出N个分数形式的有理数,其中分子和分母全是整形范围内的整数;如果是负数,则负号一定出现在最前面。
输出格式:
在一行中按照a/b
的格式输出N个有理数的平均值。注意必须是该有理数的最简分数形式,若分母为1,则只输出分子。
输入样例1:
4
1/2 1/6 3/6 -5/10
输出样例1:
1/6
输入样例2:
2
4/3 2/3
输出样例2:
1
PS:
1.难点就是累加,不然会溢出,我利用C++的__gcd()函数,非常方便
2.然后再不断地累加,直到最后的答案求出来
代码如下:
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n, a = 0, b = 0, t; //a是分子,b是分母
cin >> n;
char c;//输入'/'
int *top = new int[n];
int *bottom = new int[n];
for (int i = 0; i < n; i++) { //输入
cin >> top[i] >> c >> bottom[i];
}
a = top[0];
b = bottom[0];
for (int i = 1; i < n; i++) {
a = a * bottom[i] + top[i] * b;
b *= bottom[i];
if (a > 0)
t = __gcd(a, b);
else if (a < 0)
t = __gcd(-a, b);
//防止溢出
a /= t;
b /= t;
}
b *= n;
if (a > 0)
t = __gcd(a, b);
else if (a < 0)
t = __gcd(-a, b);
a /= t;
b /= t;
if (b == 1)
cout << a;
else
cout << a << "/" << b;
delete[]top;
delete[]bottom;
}