PTA有理数运算(函数使用)

it2023-02-05  54

给定两个有理数,你的任务是实现基本算术,即计算它们的和,差,积和商。

输入格式 共一行,以 a1/b1 a2/b2 的形式给出两个有理数。

分子和分母都在 long int 范围内,如果存在负号,则只能出现在分子前面,分母保证为非零数字。

输出格式 分别在四行输出两个有理数的和,差,积和商。

每行的格式为 number1 operator number2 = result。

请注意,所有有理数都必须采用最简形式,k a/b,其中 kk 是整数部分,而 a/ba/b 是最简分数部分。

如果数字为负,则必须将其包含在一对括号中。

如果除法中除数为 00,则输出 Inf 作为结果。

确保所有输出整数都在 long int 范围内。

输入样例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 <iostream> using namespace std; typedef long long LL; LL gcd(LL a, LL b) { return b ? gcd(b, a % b) : a; } void print(LL a, LL b) { LL d = gcd(a, b); a /= d, b /= d; if (b < 0) a *= -1, b *= -1; bool is_minus = a < 0; if (is_minus) cout << "("; if (b == 1) cout << a; else { if (abs(a) >= b) printf("%lld ", a / b), a = abs(a) % b; printf("%lld/%lld", a, b); } if (is_minus) cout << ")"; } void add(LL a, LL b, LL c, LL d) { print(a, b), cout << " + ", print(c, d), cout << " = "; a = a * d + b * c; b = b * d; print(a, b), cout << endl; } void sub(LL a, LL b, LL c, LL d) { print(a, b), cout << " - ", print(c, d), cout << " = "; a = a * d - b * c; b = b * d; print(a, b), cout << endl; } void mul(LL a, LL b, LL c, LL d) { print(a, b), cout << " * ", print(c, d), cout << " = "; a = a * c; b = b * d; print(a, b), cout << endl; } void div(LL a, LL b, LL c, LL d) { print(a, b), cout << " / ", print(c, d), cout << " = "; if (!c) puts("Inf"); else { a = a * d; b = b * c; print(a, b), cout << endl; } } int main() { LL a, b, c, d; scanf("%lld/%lld %lld/%lld", &a, &b, &c, &d); add(a, b, c, d); sub(a, b, c, d); mul(a, b, c, d); div(a, b, c, d); return 0; }
最新回复(0)