分数加减法
分数加减法
时间限制:1000 ms | 内存限制:65535 KB
难度:2
- 描述
- 编写一个C程序,实现两个分数的加减法
- 输入
- 输入包含多行数据
每行数据是一个字符串,格式是"a/boc/d"。
其中a, b, c, d是一个0-9的整数。o是运算符"+"或者"-"。
数据以EOF结束
输入数据保证合法 - 输出
- 对于输入数据的每一行输出两个分数的运算结果。
注意结果应符合书写习惯,没有多余的符号、分子、分母,并且化简至最简分数 - 样例输入
1/8+3/8 1/4-1/2 1/3-1/3
- 样例输出
1/2 -1/4 0
题目转自南阳理工学院:http://acm.nyist.edu.cn/JudgeOnline/problemset.php
个人代码(以下原创)
#include <stdio.h>
int abs(int a)
{
if (a<0)
{
return -a;
}
else
{
return a;
}
}
int psy(int a,int b)
{
if (a >= b)
{
return (a % b == 0? b: psy(b, a % b));
}
else
{
return (b % a == 0? a: psy(a, a % b));
}
}
int main()
{
int a, b, c, d;
char n;
int x, y;
int t;
while (~scanf("%d/%d%c%d/%d", &a, &b, &n, &c, &d))
{
if (b == d)
{
if (n == '+')
{
x = a+c;
if (x == 0)
{
printf("0\n");
continue;
}
y = b;
t = psy(abs(y), abs(x));
if (y/t == 1)
{
printf("%d\n", x/t);
continue;
}
printf("%d/%d\n", x/t, y/t);
continue;
}
if (n == '-')
{
x = a-c;
if (x == 0)
{
printf("0\n");
continue;
}
y = b;
t = psy(abs(y), abs(x));
if (y/t == 1)
{
printf("%d\n", x/t);
continue;
}
printf("%d/%d\n", x/t, y/t);
continue;
}
}
else
{
if (n == '+')
{
t = psy(b, d);
t = b*d/t;
x = t/b*a + t/d*c;
if (x == 0)
{
printf("0\n");
continue;
}
y = t;
t = psy(abs(y), abs(x));
if (y/t == 1)
{
printf("%d\n", x/t);
continue;
}
printf("%d/%d\n", x/t, y/t);
continue;
}
if (n == '-')
{
t = psy(b, d);
t = b*d/t;
x = t/b*a - t/d*c;
if (x == 0)
{
printf("0\n");
continue;
}
y = t;
t = psy(abs(y), abs(x));
if (y/t == 1)
{
printf("%d\n", x/t);
continue;
}
printf("%d/%d\n", x/t, y/t);
continue;
}
}
}
return 0;
}