博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PAT甲级——A1081 Rational Sum
阅读量:4541 次
发布时间:2019-06-08

本文共 1928 字,大约阅读时间需要 6 分钟。

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 (≤), 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/3

Sample Output 1:

3 1/3

Sample Input 2:

24/3 2/3

Sample Output 2:

2

Sample Input 3:

31/3 -1/6 1/8

Sample Output 3:

7/24
1 #include 
2 #include
3 #include
4 using namespace std; 5 long int gcd(long int a, long int b) 6 { 7 if(b==0) return a; 8 else return gcd(b,a%b); 9 }10 int main()11 {12 int N;13 cin >> N;14 long long Inter = 0, resa = 0, resb = 1, a, b, Div, Mul;15 for (int i = 0; i < N; ++i)16 {17 char c;18 cin >> a >> c >> b;19 resa = resa * b + a * resb;//同分相加的分子20 resb = resb * b;21 Inter += resa / resb;//简化22 resa = resa - resb * (resa / resb);23 Div = gcd(resb, resa);24 resa /= Div;25 resb /= Div;26 }27 if (Inter == 0 && resa == 0)28 cout << 0 << endl;29 else if (Inter != 0 && resa == 0)30 cout << Inter << endl;31 else if (Inter == 0 && resa != 0)32 cout << resa << "/" << resb << endl;33 else34 cout << Inter << " " << resa << "/" << resb << endl;35 return 0;36 }

 

转载于:https://www.cnblogs.com/zzw1024/p/11326646.html

你可能感兴趣的文章
这些年正Android - 母亲
查看>>
[工具] BurpSuite--XssValidator插件
查看>>
LPC1788系统时钟初始化
查看>>
channel vs mutex
查看>>
页面布局(--FlowLayout,--BorderLayout,--GridLayout)
查看>>
实验吧--web--你真的会php吗
查看>>
python中的setdefault()方法
查看>>
转 VSFTP用户权限管控
查看>>
poj2420 A Star not a Tree? 模拟退火
查看>>
微信小程序--登录授权,一键获取用户微信手机号并登录
查看>>
[转载] C#面向对象设计模式纵横谈——13. Proxy代理模式
查看>>
JqueryEasyUI浅谈---视频教程公布
查看>>
ASP.NET导出Excel,打开时提示“您尝试打开文件'XXX.xls'的格式与文件扩展名指定文件不一致”...
查看>>
Javaweb之 servlet 开发详解1
查看>>
Restore IP Addresses
查看>>
DWR框架简单应用
查看>>
KMP 学习心得-----转
查看>>
time.strftime:格式化字符串中含中文报错处理
查看>>
模态窗口缓存无法清除怎么办? 在地址上加个随机数吧"&rd=" + new Date().getTime()
查看>>
阿里的weex框架到底是什么
查看>>