你好,根据题目描述,你可以使用 C 或者 C++ 编程语言来解决这个问题。下面是一个使用 C++ 的示例代码:#include <iostream>#include <sstream>#include <vector>#include <numeric>using namespace std;// 定义有理数结构体struct Rational { int numerator; // 分子 int denominator; // 分母};// 求最大公约数int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b);}// 计算两个有理数的和Rational addRational(const Rational& r1, const Rational& r2) { Rational result; result.numerator = r1.numerator * r2.denominator + r2.numerator * r1.denominator; result.denominator = r1.denominator * r2.denominator; // 简化分数 int common = gcd(result.numerator, result.denominator); result.numerator /= common; result.denominator /= common; return result;}// 将字符串转换为有理数Rational parseRational(const string& s) { istringstream iss(s); int numerator, denominator; char slash; iss >> numerator >> slash >> denominator; // 处理负数 if (numerator < 0 && denominator < 0) { numerator = -numerator; denominator = -denominator; } else if (denominator < 0) { numerator = -numerator; denominator = -denominator; } return {numerator, denominator};}// 计算N个有理数的平均值Rational averageRational(const vector<Rational>& numbers) { Rational sum = {0, 1}; for (const auto& r : numbers) { sum = addRational(sum, r); } sum.numerator = sum.numerator / numbers.size(); // 求平均值 return sum;}int main() { int N; cin >> N; cin.ignore(); // 忽略换行符 string input; getline(cin, input); istringstream iss(input); vector<Rational> numbers; for (int i = 0; i < N; i++) { string rationalStr; iss >> rationalStr; numbers.push_back(parseRational(rationalStr)); } Rational avg = averageRational(numbers); if (avg.denominator == 1) { cout << avg.numerator << endl; } else { cout << avg.numerator << "/" << avg.denominator << endl; } return 0;}
这段代码首先定义了有理数结构体,然后实现了求最大公约数、计算有理数和、将字符串转换为有理数以及计算有理数平均值的函数。在主函数中,根据输入格式读取数据,并输出最终结果。 |