题目描述
本题要求编写程序,计算2个有理数的和、差、积、商。
输入描述:
输入在一行中按照“a1/b1 a2/b2”的格式给出两个分数形式的有理数,其中分子和分母全是整型范围内的整数,负号只可能出现在分子前,分
母不为0。
输出描述:
分别在4行中按照“有理数1 运算符 有理数2 = 结果”的格式顺序输出2个有理数的和、差、积、商。注意输出的每个有理数必须是该有理数的
最简形式“k a/b”,其中k是整数部分,a/b是最简分数部分;若为负数,则须加括号;若除法分母为0,则输出“Inf”。题目保证正确的输出中
没有超过整型范围的整数。
输入例子:
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
代码如下:
import java.util.*;
public class PAT1025 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
String tmpa = in.next();
String tmpb = in.next();
String []arr1 = tmpa.split("/");
String []arr2 = tmpb.split("/");
int a1 = Integer.parseInt(arr1[0]);
int a2 = Integer.parseInt(arr1[1]);
int b1 = Integer.parseInt(arr2[0]);
int b2 = Integer.parseInt(arr2[1]);
String left = convert(a1,a2);
String right = convert(b1,b2);
System.out.println(left+ " + " + right + " = " + cal(a1,a2,b1,b2,"+"));
System.out.println(left+ " - " + right + " = " + cal(a1,a2,b1,b2,"-"));
System.out.println(left+ " * " + right + " = " + cal(a1,a2,b1,b2,"*"));
System.out.println(left+ " / " + right + " = " + cal(a1,a2,b1,b2,"/"));
}
private static String convert(int a,int b){
if(b==0) return "Inf";
if(a==0) return "0";
StringBuilder s = new StringBuilder();
boolean flag = false;
int k = 0;
if(a<0){
s.append("(-");
a = -a;
flag = true;
}
k = a/b;
a = a%b;
if(a==0){
if(k!=0){
s.append(k);
}
if(flag==false){
return s.toString();
}
else{
return s.append(")").toString();
}
}
int gcd = gcd(a,b);
if(gcd!=0){
a = a/gcd;
b = b/gcd;
}
if(k!=0){
s.append(k).append(" ");
}
s.append(a).append("/").append(b);
if(flag){
s.append(")");
}
return s.toString();
}
private static String cal(int a1,int a2,int b1,int b2,String op){
switch(op){
case "+" :
if(a2==b2){
return convert(a1+b1,b2);
}else{
int gcd = gcd(a2,b2);
int tmp = a2*b2/gcd; //最大公约数
a1 = a1 * tmp/a2;
b1 = b1 * tmp/b2;
return convert(a1+b1,tmp);
}
case "-" :
if(a2==b2){
return convert(a1-b1,b2);
}else{
int gcd = gcd(a2,b2);
int tmp = a2*b2/gcd; //最大公约数
a1 = a1 * tmp/a2;
b1 = b1 * tmp/b2;
return convert(a1-b1,tmp);
}
case "*" :
return convert(a1*b1,a2*b2);
case "/" :
int c1 = a1*b2;
int c2 = a2*b1;
if(c2<0){
c1 = -c1;
c2 = -c2;
}
return convert(c1,c2);
default:
break;
}
return null;
}
private static int gcd(int a,int b){
while(a%b != 0){
int tmp = a%b;
a = b;
b = tmp;
}
return b;
}
}
声明:此代码思路来源于牛客网一位用户