题目链接:点击打开链接
分数四则运算
Time Limit: 1000MS
Memory Limit: 65536KB
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;
class Fenshi {
int fm;
int fz;
public Fenshi() {
super();
}
public Fenshi(int fz, int fm) {
super();
this.fm = fm;
this.fz = fz;
}
public Fenshi sum(Fenshi A) {
int newfz = fz * A.fm + fm * A.fz;
int newfm = fm * A.fm;
return new Fenshi(newfz, newfm);
}
public Fenshi del(Fenshi A) {
int newfz = fz * A.fm - fm * A.fz;
int newfm = fm * A.fm;
return new Fenshi(newfz, newfm);
}
public Fenshi xiangcheng(Fenshi A) {
int newfz = fz * A.fz;
int newfm = fm * A.fm;
return new Fenshi(newfz, newfm);
}
public Fenshi chu(Fenshi A) {
int newfz = fz * A.fm;
int newfm = fm * A.fz;
return new Fenshi(newfz, newfm);
}
}
public class Main {
static int gcd(int a, int b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
while(input.hasNext()){
String s = input.nextLine();
String[] str = s.split("\\+|\\-|\\*|\\\\");
String[] fir = str[0].split("/");
int a = Integer.parseInt(fir[0]);
int b = Integer.parseInt(fir[1]);
String[] sec = str[1].split("/");
int c = Integer.parseInt(sec[0]);
int d = Integer.parseInt(sec[1]);
Fenshi fenshi1 = new Fenshi(a,b);
Fenshi fenshi2 = new Fenshi(c,d);
Fenshi result = new Fenshi();
for(int i = 0;i <s.length();i++){
char ope = s.charAt(i);
if(ope == '+'){
result = fenshi1.sum(fenshi2);
break;
}
else if(ope == '-'){
result = fenshi1.del(fenshi2);
break;
}
else if(ope == '*'){
result = fenshi1.xiangcheng(fenshi2);
break;
}
else if(ope == '\\'){
result = fenshi1.chu(fenshi2);
break;
}
}
if (result.fz % result.fm == 0 || result.fz == 0)
System.out.println(result.fz / result.fm);
else {
int g = gcd(Math.abs(result.fz), result.fm);
System.out.printf("%d/%d\n", result.fz / g, result.fm / g);
}
}
}
}