分数四则运算
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
AC代码:
import java.util.Scanner;
class Fs {
int fz, fm;
public Fs(int x, int y) {
fz = x;
fm = y;
}
public Fs add(Fs fs) {
int Fz = fz * fs.fm + fm * fs.fz;
int Fm = fm * fs.fm;
return new Fs(Fz, Fm);
}
public Fs sub(Fs fs) {
int Fz = fz * fs.fm - fm * fs.fz;
int Fm = fm * fs.fm;
return new Fs(Fz, Fm);
}
public Fs nul(Fs fs) {
int Fz = fz * fs.fz;
int Fm = fm * fs.fm;
return new Fs(Fz, Fm);
}
public Fs div(Fs fs) {
int Fz = fz * fs.fm;
int Fm = fm * fs.fz;
return new Fs(Fz, Fm);
}
public int gcd(int n, int m) { //求最小公倍數
int r = n % m;
while (r != 0) {
n = m;
m = r;
r = n % m;
}
return m;
}
public String toString() {
int d = gcd(fz, fm);
fz /= d;
fm /= d;
String str = fz * fm < 0 ? "-" : "";
if (fz % fm == 0) {
str += Math.abs(fz / fm); //绝对值
} else {
str += Math.abs(fz) + "/" + Math.abs(fm);
}
return str;
}
}
public class Main {
public static void main(String[] args) {
Scanner mi = new Scanner(System.in);
while (mi.hasNext()) {
String str = mi.nextLine();
String[] p = str.split("\\D+");
int a = Integer.parseInt(p[0]);
int b = Integer.parseInt(p[1]);
int c = Integer.parseInt(p[2]);
int d = Integer.parseInt(p[3]);
Fs fs = new Fs(a, b);
Fs fs1 = new Fs(c, d);
String[] q = str.split("\\d+");
char op = q[2].charAt(0);
switch (op) {
case '+':
fs = fs.add(fs1);
break;
case '-':
fs = fs.sub(fs1);
break;
case '*':
fs = fs.nul(fs1);
break;
case '\\':
fs = fs.div(fs1);
break;
}
System.out.println(fs);
}
mi.close();
}
}
——————
余生还请多多指教!