原题地址
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
解题思路
基本是按照《算法笔记》里写的分数四则运算的步骤来的~
注意事项
要记得分子分母用long long,不然在相乘的时候可能会溢出(傻逼了,一开始用的int,后来忘记读取时改%d为%lld,导致输出一些奇奇怪怪的东西)
参考代码
#include <bits/stdc++.h>
using namespace std;
struct Fraction {
LL x, y;
};
LL gcd(LL a, LL b){
if (b == 0) return a;
else return gcd(b, a % b);
}
Fraction reduction(Fraction result) {
if (result.y < 0) {
result.x = -result.x;
result.y = -result.y;
}
if (abs(result.x) == 0) {
result.y = 1;
result.x = 0;
} else {
LL k = gcd(abs(result.x), abs(result.y));
result.x /= k;
result.y /= k;
}
return result;
}
Fraction add(Fraction a, Fraction b) {
Fraction result;
result.y = a.y * b.y;
result.x = a.x * b.y + b.x * a.y;
return reduction(result);
}
Fraction del(Fraction a, Fraction b) {
Fraction result;
result.y = a.y * b.y;
result.x = a.x * b.y - b.x * a.y;
return reduction(result);
}
Fraction mul(Fraction a, Fraction b) {
Fraction result;
result.y = a.y * b.y;
result.x = a.x * b.x;
return reduction(result);
}
Fraction div(Fraction a, Fraction b) {
Fraction result;
result.y = a.y * b.x;
result.x = a.x * b.y;
return reduction(result);
}
void showResult(Fraction result) {
result = reduction(result);
if (result.x < 0) printf("(");
if (result.y == 1) printf("%lld", result.x);
else if (abs(result.x) > result.y) printf("%lld %lld/%lld", result.x / result.y, abs(result.x) % result.y, result.y);
else printf("%lld/%lld", result.x, result.y);
if (result.x < 0) printf(")");
}
int main() {
Fraction a, b;
scanf("%lld/%lld %lld/%lld", &a.x, &a.y, &b.x, &b.y);
showResult(a); printf(" + "); showResult(b); printf(" = "); showResult(add(a, b)); printf("\n");
showResult(a); printf(" - "); showResult(b); printf(" = "); showResult(del(a, b)); printf("\n");
showResult(a); printf(" * "); showResult(b); printf(" = "); showResult(mul(a, b)); printf("\n");
showResult(a); printf(" / "); showResult(b); printf(" = ");
if (b.x == 0) printf("Inf");
else showResult(div(a, b));
return 0;
}