Problem Description
编写一个java程序,实现两个分数的加减法
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
1/2 -1/4 0
code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader = new Scanner(System.in);
int a, b, c, d;
String str;
char ch;
while(reader.hasNext())
{
str = reader.nextLine();
a = (int)str.charAt(0) - '0';
b = (int)str.charAt(2) - '0';
c = (int)str.charAt(4) - '0';
d = (int)str.charAt(6) - '0';
ch = str.charAt(3);
Fenshu fs1 = new Fenshu(a, b);
Fenshu fs2 = new Fenshu(c, d);
if(ch == '+')
{
System.out.println(fs1.add(fs2).toString());
}
else if(ch == '-')
{
System.out.println(fs1.sub(fs2).toString());
}
}
}
}
class Fenshu
{
private static final String GCD = null;
int a, b;
public Fenshu(int a, int b)
{
this.a = a;
this.b = b;
}
public Fenshu add(Fenshu fs)
{
int c = a*fs.b + b*fs.a;
int d = b*fs.b;
return new Fenshu(c, d);
}
public Fenshu sub(Fenshu fs)
{
int c = a*fs.b - b*fs.a;
int d = b*fs.b;
return new Fenshu(c, d);
}
public int guys(int a, int b)
{
int m = a;
int n = b;
int r = m;
while(r!=0)
{
m = n;
n = r;
r = m%n;
}
return n;
}
public String toString()
{
String str = "";
if(a%b == 0)
{
str += a/b;
}
else
{
if(a*b<0) str+="-";
int a1 = Math.abs(a);
int b1 = Math.abs(b);
int s = guys(a1, b1);
a1 = a1/s;
b1 = b1/s;
str += (a1+"/"+b1);
}
return str;
}
}
3620

被折叠的 条评论
为什么被折叠?



