您的位置:首页 > 其它

哈理工 1178 分数加减(简单的模拟)

2016-05-15 21:17 85 查看
题目链接:

http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=1178

分数加减

Time Limit: 1000 MS Memory Limit: 65536 K

Total Submit: 430(195 users) Total Accepted: 191(181 users) Rating: Special Judge: No

Description

实现两个分数之间的加减法。

Input

输入包括多组测试用例

每行是”a/b-c/d”,或”a/b+c/d”的形式。

其中a, b, c, d是0-9的整数。

输入数据保证合法。

Output

输出分数结果。

注意输出没有多余符号,若结果为正,不需要“+”号。

结果应为最简形式,例如结果应为1/2而非2/4、2而非2/1。

Sample Input

1/4-1/2

1/3-1/3

Sample Output

-1/4

0

下面是AC代码:

有个坑点,坑点就是分子是分母倍数时候的处理。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;

int gcd(int x,int y)
{
if(y==0)
return x;
return gcd(y,x%y);
}

int main()
{
int a,b,c,d;
char str;
while(~scanf("%d/%d%c%d/%d",&a,&b,&str,&c,&d))
{
int aa=a*d;
int bb=b*d;
int cc=c*b;
int dd=d*b;
int re;
if(str=='-')
re=aa-cc;
else
{
re=aa+cc;
}
if(re==0)
{
printf("0\n");
continue;
}
if(re%dd==0)
{
printf("%d\n",re/dd);
continue;
}
int ss=gcd(fabs(re),bb);
printf("%d/%d\n",re/ss,bb/ss);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: