7-35 有理数均值 (20 分)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LuYiXianSheng/article/details/82807226

7-35 有理数均值 (20 分)

本题要求编写程序,计算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

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

class Fraction {
public:
	Fraction(string frac) {
		if (frac[0] == '-') {
			isPositive = -1;
			frac = frac.substr(1, frac.length());
		}
		else
			isPositive = 1;

		int idx = frac.find('/');
		if (idx != frac.npos) {
			StrToNum(frac.substr(0, idx), Numerator);
			StrToNum(frac.substr(idx + 1, frac.length()), Denominator);
		}
		else {
			StrToNum(frac, Numerator);
			Denominator = 1;
		}
	}

	Fraction(long Numerator, long Denominator, int isPositive) {
		this->Numerator = Numerator;
		this->Denominator = Denominator;
		this->isPositive = isPositive;
	}

	Fraction add(Fraction other) {
		long newNumerator = isPositive * Numerator *
			other.getDeDenominator() + other.getPositive() *
			other.getNumerator() * Denominator;
		int tempPostive = 1;
		if (newNumerator < 0) {
			tempPostive = -1;
			newNumerator = -newNumerator;
		}
		long newDenominator = Denominator * other.getDeDenominator();
		long tempGcd = gcd(newNumerator, newDenominator);
		return Fraction(newNumerator / tempGcd, newDenominator
			/ tempGcd, tempPostive);
	}

	long gcd(long a, long b) {
		return b == 0 ? a : gcd(b, a % b);
	}

	void printAverageFraction(int n) {
		Denominator = Denominator *n;
		long tempGcd = gcd(Numerator, Denominator);
		Denominator = Denominator / tempGcd;
		Numerator = Numerator / tempGcd;
		if (isPositive < 0)
			cout << '-';
		cout << Numerator;
		if (Denominator != 1)
			cout << '/' << Denominator;
	}


	void StrToNum(const string& s, long& n){
		istringstream iss(s);
		iss >> n;
	}

	long getNumerator() {
		return Numerator;
	}

	long getDeDenominator() {
		return Denominator;
	}

	long getPositive() {
		return isPositive;
	}
private:
	long Numerator;
	long Denominator;
	long isPositive;
};


int main() {
	int count;
	string number, temp_number;
	cin >> count;
	cin >> number;
	Fraction total(number);
	for (int i = 0; i < count-1; i++) {
		cin >> temp_number;
		Fraction temp_total(temp_number);
		total = total.add(temp_total); 
		//total.printFraction();
	}
	
	total.printAverageFraction(count);

	return 0;
}

猜你喜欢

转载自blog.csdn.net/LuYiXianSheng/article/details/82807226
今日推荐