Rational Arithmetic (20)__牛客网 (nowcoder.com)

## 1、题目

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.

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.

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

## 3、代码

``````import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {

static void pr(long a, long b) {
long x = gcd(a, b);
a /= x;
b /= x;
if (b < 0) {
a *= -1;
b *= -1;
}
if (a < 0) {
if (-a % b == 0) {
System.out.print("(" + a / b + ")");
} else if (-a < b) {
System.out.print("(" + a + "/" + b + ")");
} else {
System.out.print("(" + a / b + " " + (-a + (b * (a / b))) + "/" + b + ")");
}
} else {
if (a % b == 0) {
System.out.print(a / b);
} else if (a < b) {
System.out.print(a + "/" + b);
} else {
System.out.print(a / b + " " + (a - (b * (a / b))) + "/" + b );
}
}
}
static long  gcd(long a, long b) { //辗转相除法求最大公约数
if (b == 0) {
return a;
}
long r = a % b;
return gcd(b, r);
}
static void add(long a, long b, long c, long d) {
pr(a, b);
System.out.print(" + ");
pr(c, d);
System.out.print(" = ");
pr(a * d + b * c, b * d);
}
static void minus(long a, long b, long c, long d) {
pr(a, b);
System.out.print(" - ");
pr(c, d);
System.out.print(" = ");
pr(a * d - b * c, b * d);
}
static void multiply(long a, long b, long c, long d) {
pr(a, b);
System.out.print(" * ");
pr(c, d);
System.out.print(" = ");
pr(a * c, b * d);
}
static void division(long a, long b, long c, long d) {
long m = a * d;
long n = b * c;
pr(a, b);
System.out.print(" / ");
pr(c, d);
System.out.print(" = ");
if (c == 0) {
System.out.print("Inf");
} else {
if (n < 0) {
m = m * -1; //把负号调整到分子上
n = n * -1;
}
pr(m, n);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String s = sc.nextLine();
String[] split = s.split(" ");
String[] s1 = split[0].split("/");
String[] s2 = split[1].split("/");
long a = Long.parseLong(s1[0]);
long b = Long.parseLong(s1[1]);
long c = Long.parseLong(s2[0]);
long d = Long.parseLong(s2[1]);