PAT 1034 有理数四则运算 (20分)(Java)
题目描述
本题要求编写程序,计算 2 个有理数的和、差、积、商。
输入格式:
输入在一行中按照 a1/b1 a2/b2 的格式给出两个分数形式的有理数,其中分子和分母全是整型范围内的整数,负号只可能出现在分子前,分母不为 0。
输出格式:
分别在 4 行中按照 有理数1 运算符 有理数2 = 结果
的格式顺序输出 2 个有理数的和、差、积、商。注意输出的每个有理数必须是该有理数的最简形式 k a/b
,其中 k
是整数部分,a/b
是最简分数部分;若为负数,则须加括号;若除法分母为 0,则输出 Inf
。题目保证正确的输出中没有超过整型范围的整数。
输入样例 1:
2/3 -4/2
输出样例 1:
2/3 + (-2) = (-1 1/3)
2/3 - (-2) = 2 2/3
2/3 * (-2) = (-1 1/3)
2/3 / (-2) = (-1/3)
输入样例 2:
5/3 0/6
输出样例 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
代码
package com.hbut.pat;
import java.io.*;
public class Pat_1034 {
private static long GCD(long a,long b) {
return b == 0 ? a : GCD(b , a % b);
}
private static String calculate(long a,long b) {
if(b == 0) {
return "Inf";
}
long gcd,t,x;
gcd = GCD(Math.abs(a), b);
a = a / gcd;
b = b / gcd;
t = Math.abs(a) / b;
x = Math.abs(a) - t * b;
if(t == 0 && x == 0) {
return "0";
}
if(a < 0) {
if(t != 0 && x != 0)
return "(-"+t+" "+x+"/"+b+")";
if(t != 0 && x == 0)
return "(-"+t+")";
if(t == 0 && x != 0)
return "(-"+x+"/"+b+")";
} else {
if (t != 0 && x != 0)
return t+" "+x+"/"+b;
if(t != 0 && x == 0)
return String.valueOf(t);
if(t == 0 && x != 0)
return x+"/"+b;
}
return null;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
String[] istr = br.readLine().split(" ");
String[] a = istr[0].split("/"), b = istr[1].split("/");
long a1 = Long.parseLong(a[0]), a2 = Long.parseLong(b[0]);
long b1 = Long.parseLong(a[1]), b2 = Long.parseLong(b[1]);
String A,B;
A = calculate(a1,b1);
B = calculate(a2,b2);
out.println(A + " + " + B + " = " + calculate(a1*b2+a2*b1,b1*b2));
out.flush();
out.println(A + " - " + B + " = " + calculate(a1*b2-a2*b1,b1*b2));
out.flush();
out.println(A + " * " + B + " = " + calculate(a1*a2,b1*b2));
out.flush();
out.print(A + " / " + B + " = ");
out.flush();
if(a2 < 0) {
out.print(calculate(a1 * b2 * a2 / Math.abs(a2) , b1 * Math.abs(a2)));
} else {
out.print(calculate(a1 * b2 , b1 * a2));
}
out.flush();
}
}