思路:是个水题,但是有坑。不能被题目忽悠了,题目保证正确的输出中没有超过整型范围的整数。 它只是保证结果不超出int,但是我们在运算过程中的乘法可能会超出int,直接把所有int改成long long
AC代码
#include <stdio.h>
#include <algorithm>
using namespace std;
typedef long long LL;
LL a, b, c, d;
LL e, f, g, h;
LL gcd(LL a, LL b) {
return b == 0 ? a : gcd(b, a%b);
}
void kill(LL &a, LL &b, LL &e, LL &f) {
if(b == 0) {
printf("Inf");
return;
}
if(a == 0) {
printf("0");
e = 0, f = 1;
return;
} else {
LL r = gcd(a, b);
e = a / r, f = b / r;
}
LL l = abs(e) / abs(f);
LL p = abs(e) - l * abs(f);
if(e < 0 || f < 0) {
printf("(");
}
if(e < 0 || f < 0) {
printf("-");
}
//output
if(l != 0) printf("%d", l);
if(l != 0 && p != 0) printf(" ");
if(p != 0) {
printf("%d/%d", p, abs(f));
}
if(e < 0 || f < 0) {
printf(")");
}
}
void add() {
kill(a, b, e, f);
printf(" + ");
kill(c, d, g, h);
printf(" = ");
LL p = f*h / gcd(f, h);
LL res = e * (p/f) + g * (p/h);
kill(res, p, res, p);
printf("\n");
}
void sub() {
kill(a, b, e, f);
printf(" - ");
kill(c, d, g, h);
printf(" = ");
LL p = f*h / gcd(f, h);
LL res = e * (p/f) - g * (p/h);
kill(res, p, res, p);
printf("\n");
}
void mul() {
kill(a, b, e, f);
printf(" * ");
kill(c, d, g, h);
printf(" = ");
LL res = e * g;
LL p = f * h;
kill(res, p, res, p);
printf("\n");
}
void div() {
kill(a, b, e, f);
printf(" / ");
kill(c, d, g, h);
printf(" = ");
LL res = e * h;
LL p = f * g;
kill(res, p, res, p);
printf("\n");
}
int main() {
while(scanf("%lld/%lld %lld/%lld", &a, &b, &c, &d) != EOF) {
add();
sub();
mul();
div();
}
return 0;
}
如有不当之处欢迎指出!