Whitable I Smert lnseat130:14:707 (4人创建一个Fraction类执行分数运算。要求如下: ①定义类的private成员变量:分子f1和分母f2 ②提供构造方法,创建分数; ③提供两个分数相加的运算方法; ④提供两个分数相减的运算方法; ⑤提供两个分数相乘的运算方法; ⑥提供两个分数相除的运算方法; ⑦以a/b的形式打印Fraction数; ⑧以浮点数的形式打印Fraction数; ⑨主程序中创建分数,完成分数运算,输出结果。Java代码
时间: 2024-01-22 13:21:23 浏览: 27
以下是实现上述要求的Java代码:
```java
public class Fraction {
private int f1; // 分子
private int f2; // 分母
// 构造方法
public Fraction(int f1, int f2) {
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) {
int newF1 = this.f1 * other.f2;
int newF2 = this.f2 * other.f1;
return new Fraction(newF1, newF2);
}
// 以a/b的形式打印Fraction数
public String toString() {
return this.f1 + "/" + this.f2;
}
// 以浮点数的形式打印Fraction数
public double toDouble() {
return (double) this.f1 / this.f2;
}
// 主程序
public static void main(String[] args) {
Fraction f1 = new Fraction(1, 2);
Fraction f2 = new Fraction(3, 4);
Fraction result = f1.add(f2);
System.out.println(f1.toString() + " + " + f2.toString() + " = " + result.toString());
System.out.println(f1.toDouble() + " + " + f2.toDouble() + " = " + result.toDouble());
result = f1.subtract(f2);
System.out.println(f1.toString() + " - " + f2.toString() + " = " + result.toString());
System.out.println(f1.toDouble() + " - " + f2.toDouble() + " = " + result.toDouble());
result = f1.multiply(f2);
System.out.println(f1.toString() + " * " + f2.toString() + " = " + result.toString());
System.out.println(f1.toDouble() + " * " + f2.toDouble() + " = " + result.toDouble());
result = f1.divide(f2);
System.out.println(f1.toString() + " / " + f2.toString() + " = " + result.toString());
System.out.println(f1.toDouble() + " / " + f2.toDouble() + " = " + result.toDouble());
}
}
```
运行结果:
```
1/2 + 3/4 = 5/4
0.5 + 0.75 = 1.25
1/2 - 3/4 = -1/4
0.5 - 0.75 = -0.25
1/2 * 3/4 = 3/8
0.5 * 0.75 = 0.375
1/2 / 3/4 = 2/3
0.5 / 0.75 = 0.6666666666666666
```