Rational Arithmetic(有理数运算)
题目描述:
For two rational numbers, your task is to implement the basic arithmetics, that is, to calculate their sum, difference, product and quotient.
实现对两个有理数的基本运算,包括加、减、乘、除。
输入:
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.
每个输入文件只包含一个测试用例,测试用例会给出一行数据,格式为“a1/b1 a2/b2”。
分子分母的范围都在长整型的范围内,如果数字为负,则符号只会出现在分子的前面。分母一定是非零数。
输出:
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.
针对每个测试用例,都输出四行,分别是这两个有理数的和、差、积和商,格式为“数1 操作符 数2 = 结果”。注意,所有的有理数都将遵循一个简单形式“k a/b”,其中k是整数部分,a/b是最简分数形式,如果该数为负数,则必须用括号包起来。如果除法中的除数为0,则输出“Inf”。结果中所有的整数都在long int的范围内。
示例:
输入:
2/3 -4/2
输出:
2/3 + (-2) = (-1 1/3)
2/3 – (-2) = 2 2/3
2/3 * (-2) = (-1 1/3)
2/3 / (-2) = (-1/3)
输入:
5/3 0/6
输出:
1 2/3 + 0 = 1 2/3
1 2/3 – 0 = 1 2/3
1 2/3 * 0 = 0
1 2/3 / 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还要在末尾输出”)”
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
long long a, b, c, d;
long long gcd(long long t1, long long t2) {
//gcd()是用来求最大公因数的
return t2 == 0 ? t1 : gcd(t2, t1 % t2);
}
void func(long long m, long long n) {
//判断分母或分子中是否有0
if (m * n == 0) {
printf("%s", n == 0 ? "Inf" : "0");
return ;
}
bool flag = ((m < 0 && n > 0) || (m > 0 && n < 0));//分子分母符号是否相同
m = abs(m); //求m的绝对值
n = abs(n);//求n的绝对值
long long x = m / n;//可被提取出来的整数部分
printf("%s", flag ? "(-" : "");//符号不同加(-
if (x != 0)
printf("%lld", x);//输出整数位
if (m % n =