PAT 1034 有理数四则运算
https://pintia.cn/problem-sets/994805260223102976/problems/994805287624491008
本题要求编写程序,计算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
代码:
#include <bits/stdc++.h> using namespace std; long long int gcd(long long int x,long long int y) { long long int z = x % y; while(z) { x = y; y = z; z = x % y; } return y; } void out(long long int x,long long int y) { if(y < 0) { y = y * (-1); x = x * (-1); } if(x > 0) { if(y == 1) printf("%lld", x); else { if(x % y == 0) printf("%lld", x / y); else { if(x < y) printf("%lld/%lld", x / gcd(x, y), y / gcd(x, y)); else printf("%lld %lld/%lld", x / y, (x % y) / gcd(x % y, y), y / gcd(x % y, y)); } } } else if(x == 0) printf("0"); else { if(y == 1) printf("(%lld)", x); else { if(x % y == 0) printf("(%lld)", x / y); else { if(abs(x) < y) printf("(%lld/%lld)", x / abs(gcd(x, y)), y / abs(gcd(x, y))); else printf("(%lld %lld/%lld)", x / y, abs(x) % y/gcd(abs(x) % y, y), y / gcd(abs(x) % y, y)); } } } } void add(long long int a1, long long int b1, long long int a2, long long int b2) { out(a1, b1); printf(" + "); out(a2, b2); printf(" = "); long long int a3 = a1 * b2 + a2 * b1; long long int b3 = b1 * b2; out(a3, b3); printf("\n"); } void subtract(long long int a1, long long int b1, long long int a2, long long int b2) { out(a1, b1); printf(" - "); out(a2, b2); printf(" = "); long long int a3 = a1 * b2 - a2 * b1; long long int b3 = b1 * b2; out(a3, b3); printf("\n"); } void multiplication(long long int a1, long long int b1, long long int a2, long long int b2) { out(a1, b1); printf(" * "); out(a2, b2); printf(" = "); long long int a3 = a1 * a2; long long int b3 = b1 * b2; out(a3, b3); printf("\n"); } void division(long long int a1, long long int b1, long long int a2, long long int b2) { out(a1, b1); printf(" / "); out(a2, b2); printf(" = "); if(a2 * b2 == 0) { printf("Inf"); return ; } long long int a3 = a1 * b2; long long int b3 = a2 * b1; out(a3, b3); printf("\n"); } int main() { long long int a, b, c, d; scanf("%lld/%lld %lld/%lld", &a, &b, &c, &d); add(a, b, c, d); subtract(a, b, c, d); multiplication(a, b, c, d); division(a, b, c, d); return 0; }