pat-a1081. Rational Sum (20)
来源:互联网 发布:葛底斯堡演说 知乎 编辑:程序博客网 时间:2024/06/10 18:06
以前做这种题没有用struct。。两个int相乘不会超过long long。。以前还是先约分再加的。。可以直接加了再约分。
#include<cstdio>typedef long long int LL;struct node{LL fenz,fenm;node(LL a=0,LL b=1):fenz(a),fenm(b){}};LL gcd(LL a,LL b){if(b==0) return a;return gcd(b,a%b);}void add(node& sum,const node& t){sum.fenz=sum.fenz*t.fenm+sum.fenm*t.fenz;sum.fenm=sum.fenm*t.fenm;LL k=gcd(sum.fenz,sum.fenm);sum.fenz/=k;sum.fenm/=k;}int main(){int n;node sum(0,1);LL a,b;scanf("%d",&n);while(n--){scanf("%lld/%lld",&a,&b);node temp(a,b);add(sum,temp);}int t=sum.fenz/sum.fenm;if(t*sum.fenm==sum.fenz) printf("%d\n",t);else{sum.fenz=sum.fenz%sum.fenm;if(sum.fenz<0){printf("-");sum.fenz=-sum.fenz;}if(t!=0) printf("%d ",t);if(sum.fenz) printf("%lld/%lld\n",sum.fenz,sum.fenm);}return 0;}
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:52/5 4/15 1/30 -2/60 8/3Sample Output 1:
3 1/3Sample Input 2:
24/3 2/3Sample Output 2:
2Sample Input 3:
31/3 -1/6 1/8
- PAT-A1081. Rational Sum (20)
- pat-a1081. Rational Sum (20)
- PAT A1081. Rational Sum (20)
- PAT A1081 rational sum (20)
- PAT A1081. Rational Sum (20)
- PAT A1081. Rational Sum
- 数学问题--PAT.A1081. Rational Sum
- 分数计算--PAT.A1081. Rational Arithmetic
- PAT 1081. Rational Sum (20)
- PAT 1081. Rational Sum (20)
- PAT 1081. Rational Sum(20)
- 【PAT】1081. Rational Sum (20)
- PAT 1081. Rational Sum (20)
- PAT 1081. Rational Sum (20)
- 【PAT】1081. Rational Sum (20)
- PAT 1081. Rational Sum (20)
- PAT 1081. Rational Sum (20)
- 1081. Rational Sum (20) PAT
- 爬数据
- LeetCode75
- 可见字符集ASCII
- MySQL常用知识总结
- Android Studio 2.2 新建项目常见问题
- pat-a1081. Rational Sum (20)
- 基于Spark的公安大数据实时运维技术实践
- Qt 打开文件的默认路径 QFileDialog::getOpenFileName()
- 码云git的导入项目(网上下载)和导出项目(上传到网上)
- 80老翁谈人生(315):彻夜未眠,思考对策;增强定力,反击违纪派
- 微信开发者工具下载地址
- 【JavaScript】深入理解JavaScript系列(3):全面解析Module模式
- 程序员面试金典第一章:数组与字符串(3) 确定两串乱序同构
- 图片压缩--质量压缩法&边界压缩法