[PAT A1081]Rational Sum

[PAT A1081]Rational Sum

题目描述

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.

输入样例1

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

输出样例1

3 1/3

输入样例2

2
4/3 2/3

输出样例2

2

输入样例3

3
1/3 -1/6 1/8

输出样例3

7/24

解析

题目是关于分式的运算,这类型题目是很简单的,但问题就是在于需要有一个传统的定式来解决这一系列问题,所以详情可以移步至,我会在里面写摘要一些关于分式的解法定义(来源于《算法笔记》),我会在里面详细的讲一些注释
工欲善其事必先利其器——盘点PAT中非常好用的工具(持续更新)

#include<iostream>
using namespace std;
struct Fraction {
 long long up, down;
};
long long gcd(long long a, long long b)
{
 return !b ? a : gcd(b, a%b);
}
Fraction reduction(Fraction f)
{
 if (f.down < 0) {
  f.up = -f.up;
  f.down = -f.down;
 }
 if (f.up == 0) f.down = 1;
 else {
  long long t = gcd(abs(f.up), abs(f.down));
  f.up = f.up / t;
  f.down = f.down / t;
 }
 return f;
}
void show(Fraction f) {
 reduction(f);
 if (f.down == 1) printf("%lld", f.up);
 else if (abs(f.up) > abs(f.down)) {
  printf("%lld %lld/%lld", f.up / f.down, abs(f.up) % abs(f.down), f.down);
 }
 else printf("%lld/%lld", f.up, f.down);
}
int main()
{
 int n;
 Fraction f = { 0,1 };
 scanf("%d", &n);
 for (int i = 0; i < n; i++) {
  long long up, down;
  scanf("%lld/%lld", &up, &down);
  f.up = f.up*down + f.down*up;
  f.down = f.down*down;
  f=reduction(f);
 }
 show(f);
 return 0;
}
水平有限,如果代码有任何问题或者有不明白的地方,欢迎在留言区评论;也欢迎各位提出宝贵的意见!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值