分数四则运算
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 1 1
Hint
Source
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str;
int i;
int a, b, c, d;
while(input.hasNext()) {
str = input.nextLine();
String st[] = str.split("/|\\+|-|\\*|\\\\");
a = Integer.parseInt(st[0]);
b = Integer.parseInt(st[1]);
c = Integer.parseInt(st[2]);
d = Integer.parseInt(st[3]);
Rational ra1 = new Rational(a, b);
Rational ra2 = new Rational(c, d);
for(i = 0; i < str.length(); i++) {
if(str.charAt(i) == '+') {
ra1 = ra1.add(ra2);
ra1.show();
break;
}
else if(str.charAt(i) == '-') {
ra1 = ra1.sub(ra2);
ra1.show();
break;
}
else if(str.charAt(i) == '*') {
ra1 = ra1.muti(ra2);
ra1.show();
break;
}
else if(str.charAt(i) == '\\'){
ra1 = ra1.div(ra2);
ra1.show();
break;
}
}
}
input.close();
}
}
class Rational {
int a, b;
Rational(int a, int b){
this.a = a;
this.b = b;
}
Rational add(Rational r) {
Rational R = new Rational(0, 0);
R.b = this.b * r.b;
R.a = this.b * r.a + this.a * r.b;
return R;
}
Rational sub(Rational r) {
Rational R = new Rational(0, 0);
R.b = this.b * r.b;
R.a = this.a * r.b - this.b * r.a;
return R;
}
Rational muti(Rational r) {
Rational R = new Rational(0, 0);
R.b = this.b * r.b;
R.a = this.a * r.a;
return R;
}
Rational div(Rational r) {
Rational R = new Rational(0, 0);
R.b = this.b * r.a;
R.a = this.a * r.b;
return R;
}
int f(int a, int b) {
int c;
if(a < b) {
c = a;
a = b;
b = c;
}
c = a % b;
while(c != 0) {
a = b;
b = c;
c = a % b;
}
return b;
}
void set() {
if(b != 0 && a !=0) {
int c = f(Math.abs(a),Math.abs(b));
a = a / c;
b = b/ c;
if(a < 0 && b < 0) {
a = -a;
b = -b;
}
}
}
void show(){
set();
if(a == 0) {
System.out.println("0");
}
else if(a % b == 0) {
System.out.println(a / b);
}
else {
System.out.println(a + "/" + b);
}
}
}