分数加减法
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
编写一个C程序,实现两个分数的加减法
Input
输入包含多行数据
每行数据是一个字符串,格式是"a/boc/d"。
其中a, b, c, d是一个0-9的整数。o是运算符"+"或者"-"。
数据以EOF结束
输入数据保证合法
Output
对于输入数据的每一行输出两个分数的运算结果。
注意结果应符合书写习惯,没有多余的符号、分子、分母,并且化简至最简分数
注意结果应符合书写习惯,没有多余的符号、分子、分母,并且化简至最简分数
Example Input
1/8+3/8 1/4-1/2 1/3-1/3
Example Output
1/2 -1/4 0
Hint
Author
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
//每次读一行数据
String str1 = sc.next();
//分解成字符
char[] chars = str1.toCharArray();
//将字符转换成数字
int a = chars[0] - '0';
int b = chars[2] - '0';
int c = chars[4] - '0';
int d = chars[6] - '0';
//构造2个分数
Fs fs1 = new Fs(a, b);
Fs fs2 = new Fs(c, d);
//根据运算符计算结果
Fs result = new Fs();
if (chars[3] == '+') {
result = fs1.add(fs2);
} else if (chars[3] == '-') {
result = fs1.sub(fs2);
}
if (result.fz % result.fm == 0) {
System.out.println(result.fz / result.fm);
} else {
System.out.println(result.fz + "/" + result.fm);
}
}
sc.close();
}
}
/**
* 分数类
* @author student
*
*/
class Fs {
int fz;
int fm;
public Fs(int fz, int fm) {
this.fm = fm;
this.fz = fz;
}
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 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;
}
}