[PAT解题报告] Rational Arithmetic
和1081很像,多了一些运算, 仍然是直接做,通分,别忘记最大公约数。还有输出上注意负数要加括号。
代码:
#include <cstdio> #include <cstring> #include <string> using namespace std; char s[111]; long long gcd(long long x,long long y) { return y?gcd(y, x % y):x; } void print(long long x,long long y) { if (y < 0) { x = -x; y = -y; } long long g = gcd((x < 0)?(-x):x, y); x /= g; y /= g; if (x == 0) { putchar('0'); return; } bool sign = false; if (x < 0) { sign = true; printf("(-"); x = -x; } bool have = false; if (x / y) { printf("%lld",x / y); have = true; } if (x % y) { if (have) { putchar(' '); } printf("%lld/%lld",x % y, y); } if (sign) { putchar(')'); } } int main() { long long a , b, c, d; scanf("%lld/%lld %lld/%lld",&a,&b,&c,&d); // a / b + c / d print(a, b); printf(" + "); print(c, d); printf(" = "); print(a * d + b * c, b * d); puts(""); print(a, b); printf(" - "); print(c, d); printf(" = "); print(a * d - b * c, b * d); puts(""); print(a, b); printf(" * "); print(c, d); printf(" = "); print(a * c, b * d); puts(""); print(a, b); printf(" / "); print(c, d); printf(" = "); if (c) { print(a * d, b * c); } else { printf("Inf"); } puts(""); return 0; }
原题链接: http://www.patest.cn/contests/pat-a-practise/1088