Java创建一个Fraction类执行分数运算。要求如下:
(1)用整型数表示类的private成员变量:f1和f2。
(2)提供构造方法,将分子存入f1,分母存入f2。
(3)提供两个分数相加的运算方法,结果分别存入f1和f2。
(4)提供两个分数相减的运算方法,结果分别存入f1和f2。
(5)提供两个分数相乘的运算方法,结果分别存入f1和f2。
(6)提供两个分数相除的运算方法,结果分别存入f1和f2。
(7)以a/b的形式输出Fraction数。
(8)以浮点数的形式输出Fraction数。
(9)编写主程序进行分数运算。
public class Fraction {
private int f1;
private int f2;
public Fraction(int f1, int f2) {
if (f2 == 0) {
throw new IllegalArgumentException("分母不能为0");
}
this.f1 = f1;
this.f2 = f2;
}
public Fraction add(Fraction other) {
int newF1 = this.f1 * other.f2 + other.f1 * this.f2;
int newF2 = this.f2 * other.f2;
return new Fraction(newF1, newF2);
}
public Fraction subtract(Fraction other) {
int newF1 = this.f1 * other.f2 - other.f1 * this.f2;
int newF2 = this.f2 * other.f2;
return new Fraction(newF1, newF2);
}
public Fraction multiply(Fraction other) {
int newF1 = this.f1 * other.f1;
int newF2 = this.f2 * other.f2;
return new Fraction(newF1, newF2);
}
public Fraction divide(Fraction other) {
if (other.f1 == 0) {
throw new IllegalArgumentException("除数不能为0");
}
int newF1 = this.f1 * other.f2;
int newF2 = this.f2 * other.f1;
return new Fraction(newF1, newF2);
}
public String toString() {
return f1 + "/" + f2;
}
public double toDouble() {
return (double) f1 / f2;
}
public Fraction operator_divide(Fraction other) {
return this.divide(other);
}
public static void main(String[] args) {
Fraction f1 = new Fraction(1, 2);
Fraction f2 = new Fraction(3, 4);
Fraction f3 = f1.add(f2);
System.out.println(f3);
Fraction f4 = f1.subtract(f2);
System.out.println(f4);
Fraction f5 = f1.multiply(f2);
System.out.println(f5);
Fraction f6 = f1.divide(f2);
System.out.println(f6);
}
}