A1081 Rational Sum (20 point(s))

分数计算

1. 原文

原题

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
2
5
2/5 4/15 1/30 -2/60 8/3

Sample output:

1
3 1/3

2. 解析

分数化简/最大公约数,分子分母相加后及时化简

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include<cstdio>
#include<algorithm>
using namespace std;
long long gcd(long long a,long long b){
if (b==0)
{
return a;
}else{
return gcd(b,a%b);
}
}
struct node
{
long long up,down;
};
void init(node &f){
if (f.down<0)
{
f.down=-f.down;
f.up=-f.up;
}
if (f.up==0)
{
f.down=1;
}else{
long long d=gcd(abs(f.up),abs(f.down));
f.up/=d;
f.down/=d;
}
}
int main(){
int n;
scanf("%d",&n);
node f1,f2;
scanf("%lld/%lld",&f1.up,&f1.down);
init(f1); node result;
for (int i = 1; i < n; ++i)
{
scanf("%lld/%lld",&f2.up,&f2.down);
init(f2);
result.up=f1.up*f2.down+f1.down*f2.up;
result.down=f1.down*f2.down;
init(result);
f1=result;
}
if (result.down==1)
{
printf("%lld\n",result.up);
}else if (abs(result.up)>result.down)
{
printf("%lld %lld/%lld\n",result.up/result.down,abs(result.up)%result.down,result.down);
}else{
printf("%lld/%lld\n", result.up,result.down);
}
return 0;
}

分数及时化简计算,最后化简的话,中间某个计算浮点溢出

本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1081/
  • 发布时间: 2019-09-03 12:32
  • 更新时间: 2021-10-29 14:04
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!