Problem Description
编写程序,实现两个分数的加减法
Input
输入包含多行数据;
每行数据是一个字符串,格式是"a/boc/d",其中a, b, c, d为数字(每个数字保证为正数并且不存在正号)。o是运算符"+"或者"-","*","\"。
数据以EOF结束,输入数据保证合法。
Output
直接输出结果,并且注意结果应符合书写习惯,没有多余的符号、分子、分母,并且化简至最简分数形式。
Example Input
1/100+3/100 1/4-1/2 1/3-1/3 1/2*2/1 1/2\1/2
Example Output
1/25 -1/4 0 1 1
Hint
Author
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(in.hasNext()){
String str = in.next();
char[] ch = str.toCharArray();
int g = 0;//分割加减乘除号;
int f = 0;//1代表加号,2代表减号,3代表乘,4代表除号
int i;
for(i = 0; i < str.length(); i++){
if(ch[i]=='+'){
g = i;
f = 1;
break;
}
else if(ch[i]=='-'){
g = i;
f = 2;
break;
}
else if(ch[i]=='*'){
g = i;
f = 3;
break;
}
else if(ch[i]=='\\'){
g = i;
f = 4;
break;
}
}
String s1 = str.substring(0,g);
String s2 = str.substring(g+1,str.length());
String p[] = s1.split("\\/");//分割/
String q[] = s2.split("\\/");
int a = Integer.parseInt(p[0]);
int b = Integer.parseInt(p[1]);
int c = Integer.parseInt(q[0]);
int d = Integer.parseInt(q[1]);
Fs fs1 = new Fs(a,b);
Fs fs2 = new Fs(c,d);
Fs result = new Fs();
if(f == 1)
result = fs1.add(fs2);
else if(f == 2)
result = fs1.sub(fs2);
else if(f == 3)
result = fs1.multiply(fs2);
else if(f == 4)
result = fs1.divide(fs2);
if((result.fz%result.fm)==0)
System.out.println(result.fz/result.fm);
else
System.out.println(result.fz+"/"+result.fm);
}
in.close();
}
}
class Fs{
int fz;
int fm;
public Fs(int fz, int fm){
this.fz = fz;
this.fm = fm;
}
public Fs(){}
public Fs add(Fs fs){
//加法运算
int newFz = fz*fs.fm + fm*fs.fz;
int newFm = fm*fs.fm;
int gys = gys(newFz,newFm);
return new Fs(newFz/gys,newFm/gys);
}
public Fs sub(Fs fs){
//减法运算
int newFz = fz*fs.fm - fm*fs.fz;
int newFm = fm*fs.fm;
int gys = gys(newFz,newFm);
return new Fs(newFz/gys,newFm/gys);
}
public Fs multiply(Fs fs){
//乘法运算
int newFz = fz*fs.fz;
int newFm = fm*fs.fm;
int gys = gys(newFz,newFm);
return new Fs(newFz/gys,newFm/gys);
}
public Fs divide(Fs fs){
//除法运算
int newFz = fz*fs.fm;
int newFm = fm*fs.fz;
int gys = gys(newFz,newFm);
return new Fs(newFz/gys,newFm/gys);
}
public int gys(int a,int b){
//求最大公约数
int m = Math.max(Math.abs(a), Math.abs(b));
int n = Math.min(Math.abs(a), Math.abs(b));
int r;
while(n!=0){
r = m%n;
m = n;
n = r;
}
return m;
}
}