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");
		}
	}
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值