PAT(Advanced) 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.

解答:对于该题,我们可以用结构体来保存一个分数的上下标,然后分数相加,相加后需要化简,最后根据题目要求输出结果。

这道题真的是C语言模块化编程的优势体现啊,很棒的题目。

AC代码如下:

#include<cstdio>
#include<iostream>
#include<cmath>

using namespace std;

typedef struct{
	int up, down;
}fraction;

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

fraction reduction(fraction re)
{	
	if(re.up != 0)
	{
		int tmp = gcd(abs(re.up), abs(re.down));
	
		re.up /= tmp;
		re.down /= tmp;
	}
	else
	{
		re.down = 1;
	}
	return re;	
}

fraction add(fraction t, fraction sum)
{
	fraction tmp;
	tmp.up = t.up * sum.down + t.down * sum.up;
	tmp.down = sum.down * t.down;
	tmp = reduction(tmp);
	
	return tmp;
}

int main()
{
	int n;
	fraction sum;
	
	sum.up = 0; sum.down = 1;
	
	scanf("%d", &n);
	for(int i = 0; i < n; ++i)
	{
		fraction t;
		scanf("%d/%d", &t.up, &t.down);
		
		sum = add(t, sum);
	}
	
	int integer = sum.up / sum.down; 
	sum.up %= sum.down;
	if(integer == 0)
	{
		if(sum.up != 0)
			printf("%d/%d\n", sum.up, sum.down);
		else
			printf("0\n");
	}
	else
	{
		if(sum.up != 0)
			printf("%d %d/%d\n", integer, sum.up, sum.down);
		else
			printf("%d\n", integer);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37597345/article/details/82349247