PAT 甲级 1081 Rational Sum (20 分)

题目描述

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

输入

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.

输出

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.

思路

分数的加减法,注意约分(最大公约数)

代码

#include<iostream>
#include<cstdio>
#include<stdlib.h>
using namespace std;
typedef struct node {
    
    
	int num;
	int den;
}Ration;
Ration ration[1000];
void yue(int i)
{
    
    
	int a = ration[i].num;
	int b = ration[i].den;
	int c = ration[i].num % ration[i].den;
	while (c)
	{
    
    
		a = b;
		b = c;
		c = a % b;
	}
	ration[i].num /= b;
	ration[i].den /= b;
}
int main()
{
    
    
	int N;
	cin >> N;
	for (int i = 0; i < N; i++)
	{
    
    
		scanf("%d/%d", &ration[i].num, &ration[i].den);
	}
	ration[N].num = 0;
	ration[N].den = 1;
	for (int i = 0; i < N; i++)
	{
    
    
		ration[i + 1].num = ration[i].num * ration[i + 1].den + ration[i + 1].num * ration[i].den;
		ration[i + 1].den = ration[i].den * ration[i + 1].den;
		yue(i + 1);
	}
	int y = ration[N].num / ration[N].den;
	ration[N].num = ration[N].num % ration[N].den;
	if (y > 0)
	{
    
    
		printf("%d", y);
	}
	if (ration[N].num != 0)
	{
    
    
		if (y != 0)
		{
    
    
			printf(" ");
		}
		printf("%d/%d\n", ration[N].num, ration[N].den);
	}
	else
	{
    
    
		if (y == 0)
		{
    
    
			printf("0\n");
		}
	}
	
}

Guess you like

Origin blog.csdn.net/qq_45478482/article/details/120096231