本题要求编写程序,计算 2 个有理数的和、差、积、商。
输入格式:
输入在一行中按照 a1/b1 a2/b2
的格式给出两个分数形式的有理数,其中分子和分母全是整型范围内的整数,负号只可能出现在分子前,分母不为 0。
输出格式:
分别在 4 行中按照 有理数1 运算符 有理数2 = 结果
的格式顺序输出 2 个有理数的和、差、积、商。注意输出的每个有理数必须是该有理数的最简形式 k a/b
,其中 k
是整数部分,a/b
是最简分数部分;若为负数,则须加括号;若除法分母为 0,则输出 Inf
。题目保证正确的输出中没有超过整型范围的整数。
输入样例 1:
2/3 -4/2
输出样例 1:
2/3 + (-2) = (-1 1/3)
2/3 - (-2) = 2 2/3
2/3 * (-2) = (-1 1/3)
2/3 / (-2) = (-1/3)
输入样例 2:
5/3 0/6
输出样例 2:
1 2/3 + 0 = 1 2/3
1 2/3 - 0 = 1 2/3
1 2/3 * 0 = 0
1 2/3 / 0 = Inf
作者: CHEN, Yue
单位: 浙江大学
时间限制: 200 ms
内存限制: 64 MB
代码长度限制: 16 KB
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string>
#include <map>
using namespace std;
const int maxn = ;
struct num{
long long k = ;
long long up;
long long down;
};
int gcd(long long a, long long b){
return b == ? a : gcd(b, a % b);
}
num add(num n1, num n2){
num res;
res.down = n1.down*n2.down;
res.up = n1.down*n2.up + n1.up*n2.down;
return res;
}
num sub(num n1, num n2){
num res;
res.down = n1.down*n2.down;
res.up = n2.down*n1.up - n2.up*n1.down;
return res;
}
num mul(num n1, num n2){
num res;
res.down = n1.down*n2.down;
res.up = n1.up*n2.up;
return res;
}
num dive(num n1, num n2){
num res;
res.down = n1.down*n2.up;
res.up = n1.up*n2.down;
if (res.down < ){
res.down = - * res.down;
res.up = - * res.up;
}
return res;
}
void clean(num n){
int flag = ;
n.k = n.up / n.down;
if (n.up < ){
n.up = -n.up;
flag = ;
}
n.up = n.up%n.down;
int g = abs(gcd(n.up, n.down));
n.up /= g;
n.down /= g;
if (flag == ){
printf("(");
}
if (n.k != ){
printf("%lld", n.k);
if (n.up != ){
printf(" %lld/%lld", n.up, n.down);
}
}
else{
if (n.up != ){
if (flag == )printf("-");
printf("%lld/%lld", n.up, n.down);
}
else{
printf("");
}
}
if (flag == ){
printf(")");
} }
int main(){
num n1, n2;
scanf("%lld/%lld %lld/%lld", &n1.up, &n1.down, &n2.up, &n2.down);
/*int g = abs(gcd(n1.up, n1.down));
n1.up /= g;
n1.down /= g;
g = abs(gcd(n2.up, n2.down));
n2.up /= g;
n2.down /= g;*/
num q, w, e, r;
q = add(n1, n2);
clean(n1);
printf(" + ");
clean(n2);
printf(" = ");
clean(q);
printf("\n"); w = sub(n1, n2);
clean(n1);
printf(" - ");
clean(n2);
printf(" = ");
clean(w);
printf("\n"); r = mul(n1, n2);
clean(n1);
printf(" * ");
clean(n2);
printf(" = ");
clean(r);
printf("\n"); if (n2.up != ){
e = dive(n1, n2);
clean(n1);
printf(" / ");
clean(n2);
printf(" = ");
clean(e);
printf("\n");
}
else{
clean(n1);
printf(" / ");
clean(n2);
printf(" = Inf\n"); } system("pause");
}
注意点:这道题的坑有两个,一个是int不够大,两个大int乘起来就爆了,要用long long,long long 的输入输出要用lld。第二个是约分,求最大公约数,遍历就超时了,要用辗转相除法,一定要记住!!!