java 创建一个Fraction类执行分数运算。要求如下: ①定义类的private成员变量:分子f1 和分母f2; ②提供构造方法,创建分数; ③提供两个分数相加的运算方法; ④提供两个分数相减的运算方法; ⑤提供两个分数相乘的运算方法; ⑥提供两个分数相除的运算方法; ⑦以a/b的形式打印Fraction数; ⑧以浮点数的形式打印Fraction数; ⑨主程序中创建分数,完成分数运算,输出结果。
时间: 2024-02-01 11:13:51 浏览: 59
以下是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的形式打印分数
public String toString() {
return this.f1 + "/" + this.f2;
}
// 以浮点数的形式打印分数
public double toDouble() {
return (double) this.f1 / this.f2;
}
public static void main(String[] args) {
// 创建分数
Fraction f1 = new Fraction(3, 4);
Fraction f2 = new Fraction(1, 2);
// 分数运算
Fraction sum = f1.add(f2);
Fraction difference = f1.subtract(f2);
Fraction product = f1.multiply(f2);
Fraction quotient = f1.divide(f2);
// 输出结果
System.out.println(f1 + " + " + f2 + " = " + sum);
System.out.println(f1 + " - " + f2 + " = " + difference);
System.out.println(f1 + " * " + f2 + " = " + product);
System.out.println(f1 + " / " + f2 + " = " + quotient);
}
}
```
运行上述代码,输出结果如下:
```
3/4 + 1/2 = 5/4
3/4 - 1/2 = 1/4
3/4 * 1/2 = 3/8
3/4 / 1/2 = 3/2
```
阅读全文