本题要求编写程序,计算 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 = 100010; struct num{ long long k = 0; long long up; long long down; }; int gcd(long long a, long long b){ return b == 0 ? 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 < 0){ res.down = -1 * res.down; res.up = -1 * res.up; } return res; } void clean(num n){ int flag = 0; n.k = n.up / n.down; if (n.up < 0){ n.up = -n.up; flag = 1; } n.up = n.up%n.down; int g = abs(gcd(n.up, n.down)); n.up /= g; n.down /= g; if (flag == 1){ printf("("); } if (n.k != 0){ printf("%lld", n.k); if (n.up != 0){ printf(" %lld/%lld", n.up, n.down); } } else{ if (n.up != 0){ if (flag == 1)printf("-"); printf("%lld/%lld", n.up, n.down); } else{ printf("0"); } } if (flag == 1){ 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(" "); w = sub(n1, n2); clean(n1); printf(" - "); clean(n2); printf(" = "); clean(w); printf(" "); r = mul(n1, n2); clean(n1); printf(" * "); clean(n2); printf(" = "); clean(r); printf(" "); if (n2.up != 0){ e = dive(n1, n2); clean(n1); printf(" / "); clean(n2); printf(" = "); clean(e); printf(" "); } else{ clean(n1); printf(" / "); clean(n2); printf(" = Inf "); } system("pause"); }
注意点:这道题的坑有两个,一个是int不够大,两个大int乘起来就爆了,要用long long,long long 的输入输出要用lld。第二个是约分,求最大公约数,遍历就超时了,要用辗转相除法,一定要记住!!!