1088 Rational Arithmetic
For two rational numbers, your task is to implement the basic arithmetics, that is, to calculate their sum, difference, product and quotient.
Input Specification:
Each input file contains one test case, which gives in one line the two rational numbers in the format a1/b1 a2/b2. The numerators and the denominators are all in the range of long int. If there is a negative sign, it must appear only in front of the numerator. The denominators are guaranteed to be non-zero numbers.
Output Specification:
For each test case, print in 4 lines the sum, difference, product and quotient of the two rational numbers, respectively. The format of each line is number1 operator number2 = result. Notice that all the rational numbers must be in their simplest form k a/b, where k is the integer part, and a/b is the simplest fraction part. If the number is negative, it must be included in a pair of parentheses. If the denominator in the division is zero, output Inf as the result. It is guaranteed that all the output integers are in the range of long int.
Sample Input 1:
2/3 -4/2
Sample Output 1:
2/3 + (-2) = (-1 1/3)
2/3 - (-2) = 2 2/3
2/3 * (-2) = (-1 1/3)
2/3 / (-2) = (-1/3)
Sample Input 2:
5/3 0/6
Sample Output 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>
#include<vector>
#include<string>
using namespace std;
long long int gcd(long long int c1,long long int c2) { //最大公因数
if (c1 < 0)c1 = c1 * (-1);
if (c2 < 0)c2 = c2 * (-1);
long long int a, b, r;
a = c1 >= c2 ? c1 : c2;
b = c1 < c2 ? c1 : c2;
r = a % b;
while (r != 0) {
a = b;
b = r;
r = a % b;
}
return b;
}
void simplyfy(long long int &a,long long int &b) {
if (a != 0&&b!=0) {
long long int c = a, d = b;
long long int temp_gcd = gcd(c, d);
a = a / temp_gcd;
b = b / temp_gcd;
}
}
string func(long long int a,long long int b) {
if (b == 0) return "Inf";
if (a == 0)return "0";
bool negative = true;
if (a < 0 && b < 0)negative = false;
else if (a > 0 && b > 0)negative = false;
else negative = true;
a = abs(a); b = abs(b);
string s;
if (a != 0 && b != 0) {
simplyfy(a, b);
}
long long int flag = 0, xishu = a / b, fenzhi = a % b;
//系数
if (xishu != 0) {
s = s + to_string(xishu);
flag = 1;
}
//分子
if (fenzhi != 0){
if (flag) s = s + " ";
s = s + to_string(fenzhi);
s += "/";
s += to_string(b);
}
//负数
if (negative) {
s = "(-" + s;
s = s + ")";
}
return s;
}
int main() {
long long int a, b, c, d;
scanf_s("%lld/%lld %lld/%lld", &a, &b, &c, &d);
cout << func(a, b) << " + " << func(c, d) << " = " << func(a*d+b*c, b*d) << endl;
cout << func(a, b) << " - " << func(c, d) << " = " << func(a*d-b*c, b*d) << endl;
cout << func(a, b) << " * " << func(c, d) << " = " << func(a*c, b*d) << endl;
cout << func(a, b) << " / " << func(c, d) << " = " << func(a*d,b*c);
return 0;
}
本文介绍了一个有理数运算的实现方案,包括加、减、乘、除四种基本运算。输入为两个有理数,输出为运算结果,结果需简化至最简形式。文章提供了一段参考代码,实现了有理数的加法、减法、乘法和除法,并考虑了负数和除数为零的情况。
688

被折叠的 条评论
为什么被折叠?



