1081 Rational Sum (20分)【分数的四则运算】

1081 Rational Sum (20分)

Given N rational numbers in the form numerator/denominator, you are supposed to calculate their sum.

Input Specification:

Each input file contains one test case. Each case starts with a positive integer N (≤100), followed in the next line N rational numbers a1/b1 a2/b2 ... where all the numerators and denominators are in the range of long int. If there is a negative number, then the sign must appear in front of the numerator.

Output Specification:

For each test case, output the sum in the simplest form integer numerator/denominator where integer is the integer part of the sum, numerator < denominator, and the numerator and the denominator have no common factor. You must output only the fractional part if the integer part is 0.

Sample Input 1:

5
2/5 4/15 1/30 -2/60 8/3

Sample Output 1:

3 1/3

Sample Input 2:

2
4/3 2/3

Sample Output 2:

2

Sample Input 3:

3
1/3 -1/6 1/8

Sample Output 3:

7/24

 解题思路:

这道题会给我们n个分数,要求我们求n个分数的和,注意分数前面可能会有负号。

这是一道模拟分数加法的题目,我们只需要注意分数的计算公式是:

result = \frac{f1.up*f2.down+f2.up*f1.down}{f1.down*f2.down}

然后就是注意每次计算后要注意约分!

#include<iostream>
#include<cstdio>
#include<math.h>
using namespace std;

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

int main()
{
	int n;
	cin >> n;
	int up, down;
	scanf("%d/%d", &up, &down);
	int tmp = gcd(up, down);
	up = up / tmp;
	down = down / tmp;
	for (int i = 1; i < n; i++)
	{
		int up_tmp, down_tmp;
		scanf("%d/%d", &up_tmp, &down_tmp);
		up = up*down_tmp + down*up_tmp;       //计算分子
		down = down*down_tmp;                         //计算分母
		tmp = gcd(down, up);
		up = up / tmp;                                           //分子分母约分
		down = down / tmp;
	}
	if (up%down == 0)                                        //如果是整数
		cout << up / down << endl;
	else                                                                //如果是分数
	{ 
		if (abs(up) > abs(down))                           //如果是假分数
		{
			if (up > 0)
				cout << up / down << " " << up - up / down*down << "/" << down << endl;
			else
			{
				up = -up;
				cout << "-" << up / down << " " << up - up / down*down << "/" << down << endl;
			}
		}
		else
			cout << up << "/" << down << endl;
	}
	return 0;
}

 

posted @ 2020-04-13 17:22  Hu_YaYa  阅读(15)  评论(0)    收藏  举报