PAT A1088 Rational Arithmetic (20point(s))

Scroll Down

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 <cmath>

using namespace std;

long long a, b, c, d;

long long gcd(long long t1, long long t2) {
	return t2 == 0 ? t1 : gcd(t2, t1%t2);
}

void func(long long m, long long n) {
	if (m*n == 0) {
		printf("%s", n == 0 ? "Inf" : "0");
		return;
	}
	bool flag = ((m > 0 && n < 0) || (m < 0 && n > 0));// 负数标志
	m = abs(m);
	n = abs(n);
	long long x = m / n;
	printf("%s", flag ? "(-" : ""); // 如果是负数,要打印(-c a/b)的形式,所以先打印(-
	if (x != 0) printf("%lld", x);// 分子大于分母, 则打印c
	if (m%n == 0) {// 分子恰好被分母整除,结束
		if (flag) printf(")");
		return;
	}
	if (x != 0) printf(" "); // 如果没打印x,不能打印空格
	m = m - x * n;// 分子剩余部分
	long long t = gcd(m, n);// 约分
	m = m / t; n = n / t;
	printf("%lld/%lld%s", m, n, flag ? ")" : "");
	
}
int main() {
	scanf("%lld/%lld %lld/%lld", &a, &b, &c, &d);
	func(a, b); printf(" + "); func(c, d); printf(" = "); func(a * d + b * c, b * d); printf("\n");
	func(a, b); printf(" - "); func(c, d); printf(" = "); func(a * d - b * c, b * d); printf("\n");
	func(a, b); printf(" * "); func(c, d); printf(" = "); func(a * c, b * d); printf("\n");
	func(a, b); printf(" / "); func(c, d); printf(" = "); func(a * d, b * c);
	return 0;
}