分数加减法
Problem Description
编写一个C程序,实现两个分数的加减法
Input
输入包含多行数据
每行数据是一个字符串,格式是"a/boc/d"。
其中a, b, c, d是一个0-9的整数。o是运算符"+"或者"-"。
数据以EOF结束
输入数据保证合法
Output
注意结果应符合书写习惯,没有多余的符号、分子、分母,并且化简至最简分数
Sample Input
1/8+3/8 1/4-1/2 1/3-1/3
Sample Output
import java.util.Scanner;
class FS {
int a; // 分子
int b; // 分母
public FS(int a, int b) {
this.a = a;
this.b = b;
}
public FS add(FS fs) {
int c = a * fs.b + b * fs.a;
int d = b * fs.b;
return new FS(c, d);
}
public FS sub(FS fs) {
int c = a * fs.b - b * fs.a;
int d = b * fs.b;
return new FS(c, d);
}
public int gys(int m, int n) // 最大公约数
{
int r = m;
while (r != 0) {
m = n;
n = r;
r = m % n;
}
return n;
}
public String toString() // 输出 a/b的最简,符合阅读习惯
{
String str = "";
if (a % b == 0) {
str += a / b;
} else {
if (a * b < 0) {
str += "-";
}
// |a|/|b|
int a1 = Math.abs(a);
int b1 = Math.abs(b);
int s = gys(a1, b1);
a1 = a1 / s;
b1 = b1 / s;
str = str + a1 + "/" + b1;
}
return str;
}
}
public class Main {
public static void main(String[] args) {
// 输入
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String str = sc.nextLine(); // 1/8+3/8
// 操作与调用
int a = str.charAt(0) - '0';
int b = str.charAt(2) - '0';
int c = str.charAt(4) - '0';
int d = str.charAt(6) - '0';
char op = str.charAt(3);
FS fs1 = new FS(a, b);
FS fs2 = new FS(c, d);
// 输出
if (op == '+') {
System.out.println(fs1.add(fs2));
} else {
System.out.println(fs1.sub(fs2));
}
}
}
}
1/2-1/4