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
import java.util.Scanner;
class FS{
int a;
int b;
public FS(int a, int b) {
//super();
this.a = a;
this.b = b;
}
public FS add(FS fs){
int c = a*fs.b+b*fs.a;
int d = b*fs.b;
return new FS(c, d);
}
public FS sub(FS fs){
int c = a*fs.b-b*fs.a;
int d = b*fs.b;
return new FS(c, d);
}
public FS mul(FS fs){
int c = a*fs.a;
int d = b*fs.b;
return new FS(c, d);
}
public FS chu(FS fs){
int c = a*fs.b;
int d = b*fs.a;
return new FS(c, d);
}
public int gys(int m, int n){
if(m>n){
int t=m;m=n;n=t;
}
while(m!=0){
int t = n%m;
n = m;
m = t;
}
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 = gys(a1, b1);
a1 = a1/s;
b1 = b1/s;
str+=a1+"/"+b1;
}
return str;
}
}
public class Main {
public static void main(String[] args) {
//in
Scanner reader = new Scanner(System.in);
while(reader.hasNext()){
String str = reader.nextLine();
String[] split = str.split("\\D");
int a=Integer.parseInt(split[0]);
int b=Integer.parseInt(split[1]);
int c=Integer.parseInt(split[2]);
int d=Integer.parseInt(split[3]);
String[] split1 = str.split("\\d+");
char op = split1[2].charAt(0);
FS fs1 = new FS(a, b);
FS fs2 = new FS(c, d);
if(op=='+'){
System.out.println(fs1.add(fs2));
}
else if(op=='-'){
System.out.println(fs1.sub(fs2));
}
else if(op=='*') {
System.out.println(fs1.mul(fs2));
}
else if(op=='\\') {
System.out.println(fs1.chu(fs2));
}
}
}
}