Problem Description
编写程序,实现两个分数的加减法
Input
输入包含多行数据;
每行数据是一个字符串,格式是"a/boc/d",其中a, b, c, d为数字(每个数字保证为正数并且不存在正号)。o是运算符"+"或者"-","*","\"。
数据以EOF结束,输入数据保证合法。
Output
直接输出结果,并且注意结果应符合书写习惯,没有多余的符号、分子、分母,并且化简至最简分数形式。
Sample Input
1/100+3/100 1/4-1/2 1/3-1/3 1/2*2/1 1/2\1/2
Sample Output
1/25 -1/4 0 1 1
code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader = new Scanner(System.in);
int a, b, c, d;
String str;
char ch = 0;
while(reader.hasNext())
{
str = reader.nextLine();
for(int i = 0;i<str.length();i++)
{
if(str.charAt(i) == '+'||str.charAt(i) == '-'||str.charAt(i) == '*'||str.charAt(i) == '\\')
{
ch = str.charAt(i);
break;
}
}
String str2[] = str.split("\\+|-|\\*|/|\\\\");
a = Integer.parseInt(str2[0]);
b = Integer.parseInt(str2[1]);
c = Integer.parseInt(str2[2]);
d = Integer.parseInt(str2[3]);
Fenshu fs1 = new Fenshu(a, b);
Fenshu fs2 = new Fenshu(c, d);
if(ch == '+')
{
System.out.println(fs1.add(fs2).toString());
}
else if(ch == '-')
{
System.out.println(fs1.sub(fs2).toString());
}
else if(ch == '*')
{
System.out.println(fs1.cheng(fs2).toString());
}
else if(ch == '\\')
{
System.out.println(fs1.chu(fs2).toString());
}
}
}
}
class Fenshu
{
private static final String GCD = null;
int a, b;
public Fenshu(int a, int b)
{
this.a = a;
this.b = b;
}
public Fenshu add(Fenshu fs)
{
int c = a*fs.b + b*fs.a;
int d = b*fs.b;
return new Fenshu(c, d);
}
public Fenshu sub(Fenshu fs)
{
int c = a*fs.b - b*fs.a;
int d = b*fs.b;
return new Fenshu(c, d);
}
public Fenshu cheng(Fenshu fs)
{
return new Fenshu(a*fs.a, b*fs.b);
}
public Fenshu chu(Fenshu fs)
{
return new Fenshu(a*fs.b, b*fs.a);
}
public int guys(int a, int b)
{
int m = a;
int n = b;
int r = m;
while(r!=0)
{
m = n;
n = r;
r = m%n;
}
return n;
}
public String toString()
{
String str = "";
if(a%b == 0)
{
str += a/b;
}
else
{
if(a*b<0) str+="-";
int a1 = Math.abs(a);
int b1 = Math.abs(b);
int s = guys(a1, b1);
a1 = a1/s;
b1 = b1/s;
str += (a1+"/"+b1);
}
return str;
}
}