用java修改RationalNumber类,使其实现Comparable接口。为了实现比较,首先计算两个RationalNumber对象(分子和分母)的浮点数值,然后以0.0001为误差精度进行比较。编写一个main驱动方法,测试你的修改结果。
时间: 2024-02-13 11:02:02 浏览: 61
好的,我来帮你解决这个问题。
以下是修改后的RationalNumber类实现Comparable接口的代码:
```java
public class RationalNumber implements Comparable<RationalNumber> {
private int numerator;
private int denominator;
public RationalNumber(int numerator, int denominator) {
if (denominator == 0) {
throw new IllegalArgumentException("Denominator cannot be zero.");
}
int gcd = gcd(numerator, denominator);
this.numerator = numerator / gcd;
this.denominator = denominator / gcd;
if (this.denominator < 0) {
this.numerator = -this.numerator;
this.denominator = -this.denominator;
}
}
public RationalNumber add(RationalNumber other) {
int newNumerator = numerator * other.denominator + denominator * other.numerator;
int newDenominator = denominator * other.denominator;
return new RationalNumber(newNumerator, newDenominator);
}
public RationalNumber subtract(RationalNumber other) {
int newNumerator = numerator * other.denominator - denominator * other.numerator;
int newDenominator = denominator * other.denominator;
return new RationalNumber(newNumerator, newDenominator);
}
public RationalNumber multiply(RationalNumber other) {
int newNumerator = numerator * other.numerator;
int newDenominator = denominator * other.denominator;
return new RationalNumber(newNumerator, newDenominator);
}
public RationalNumber divide(RationalNumber other) {
int newNumerator = numerator * other.denominator;
int newDenominator = denominator * other.numerator;
return new RationalNumber(newNumerator, newDenominator);
}
private int gcd(int a, int b) {
if (b == 0) {
return Math.abs(a);
} else {
return gcd(b, a % b);
}
}
public String toString() {
return numerator + "/" + denominator;
}
public double toDouble() {
return (double) numerator / denominator;
}
public int compareTo(RationalNumber other) {
double thisValue = this.toDouble();
double otherValue = other.toDouble();
if (Math.abs(thisValue - otherValue) < 0.0001) {
return 0;
} else if (thisValue < otherValue) {
return -1;
} else {
return 1;
}
}
public static void main(String[] args) {
RationalNumber r1 = new RationalNumber(1, 2);
RationalNumber r2 = new RationalNumber(3, 4);
RationalNumber r3 = new RationalNumber(2, 4);
System.out.println("r1 = " + r1);
System.out.println("r2 = " + r2);
System.out.println("r3 = " + r3);
System.out.println("r1.compareTo(r2) = " + r1.compareTo(r2));
System.out.println("r2.compareTo(r1) = " + r2.compareTo(r1));
System.out.println("r1.compareTo(r3) = " + r1.compareTo(r3));
System.out.println("r3.compareTo(r1) = " + r3.compareTo(r1));
System.out.println("r2.compareTo(r3) = " + r2.compareTo(r3));
System.out.println("r3.compareTo(r2) = " + r3.compareTo(r2));
}
}
```
我们实现了`Comparable<RationalNumber>`接口,并在`compareTo`方法中,首先计算了两个RationalNumber对象的浮点数值,然后以0.0001为误差精度进行比较。如果两个对象的浮点数值差距小于0.0001,我们就认为它们相等,返回0;如果前者小于后者,返回-1;否则返回1。
在main方法中,我们测试了三个RationalNumber对象之间的比较结果。
希望这能帮到你!
阅读全文