1088. Rational Arithmetic (20)-PAT甲级真题

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

题目大意:输入在一行中按照“a1/b1 a2/b2”的格式给出两个分数形式的有理数,其中分子和分母全是整型范围内的整数,负号只可能出现在分子前,分母不为0,分别在4行中按照“有理数1 运算符 有理数2 = 结果”的格式顺序输出2个有理数的和、差、积、商。注意输出的每个有理数必须是该有理数的最简形式“k a/b”,其中k是整数部分,a/b是最简分数部分;若为负数,则须加括号;若除法分母为0,则输出“Inf”~题目保证正确的输出中没有超过整型范围的整数~

分析:func(m, n)的作用是对m/n的分数进行化简,gcd(t1, t2)的作用是计算t1和t2的最大公约数~在func函数中,先看m和n里面是否有0(即m*n是否等于0),如果分母n=0,输出Inf,如果分子m=0,输出”0″~flag表示m和n是否异号,flag=true表示后面要添加负号”(-“和括号”)”,再将m和n都转为abs(m)和abs(n),即取他们的正数部分方便计算~x = m/n为m和n的可提取的整数部分,先根据flag的结果判断是否要在前面追加”(-“,然后根据x是否等于0判断要不要输出这个整数位,接着根据m%n是否等于0的结果判断后面还有没有小分数,如果m能被n整除,表示没有后面的小分数,那么就根据flag的结果判断要不要加”)”,然后直接return~如果有整数位,且后面有小分数,则要先输出一个空格,接着处理剩下的小分数,先把m分子减去已经提取出的整数部分,然后求m和n的最大公约数t,让m和n都除以t进行化简~最后输出“m/n”,如果flag==true还要在末尾输出”)”

注意:判断m和n是否异号千万不要写成判断m*n是否小于0,因为m*n的结果可能超过了long long int的长度,导致溢出大于0,如果这样写的话会有一个测试点无法通过~((⊙o⊙)嗯为了这一个测试点找bug找到凌晨两三点的就是我…我好菜啊.jpg)

❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼

❤ 点击这里 -> 订阅《从放弃C语言到使用C++刷算法的简明教程》by 柳婼

❤ 点击这里 -> 订阅PAT甲级乙级、蓝桥杯、GPLT天梯赛、LeetCode题解离线版