分数四则运算
Time Limit: 1000 ms Memory Limit: 65536 KiB
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
import java.util.*;
public class Main {
public static int gcd(int a, int b){
if(b == 0)
return a;
return gcd(b, a%b);
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
while(cin.hasNext()){
String str = cin.next();
String []num = str.split("\\D+");
String []ch = str.split("\\d+");
int []numbers = new int[10];
for(int i = 0; i < 4; i++){
numbers[i] = Integer.parseInt(num[i]);
}
char op = ch[2].charAt(0);
int fen = 0, mu = 0;
int a = numbers[0];
int b = numbers[1];
int c = numbers[2];
int d = numbers[3];
if(op == '+'){
mu = b*d/gcd(b, d);
fen = mu/b*a + mu/d*c;
}
else if(op == '-'){
mu = b*d/gcd(b, d);
fen = mu/b*a - mu/d*c;
}
else if(op == '*'){
fen = a*c;
mu = b*d;
}
else if(op == '\\'){
fen = a*d;
mu = b*c;
}
int aa = Math.abs(gcd(fen, mu));
fen /= aa;
mu /= aa;
if(fen == mu || fen == -mu)
System.out.println(fen/mu);
else if(fen == 0)
System.out.println(0);
else
System.out.println(fen+"/"+mu);
}
}
}