修改 RationalNumber 类,使其实现 Comparable 接口。为了实现比较,首先计算两个 RationalNumber 对象(分子和分母)的浮点数等价值,然后以0.0001为误差精度进行比较。编写一个 main 驱动方法,测试你的修改结果。
本题重点是实现 Comparable 接口,计算对象浮点值以万分之一为精度进行比较。
public int compareTo(RationalNumber op2)
double nu1, de1, nu2, de2; nu1 = numerator; de1 = denominator; nu2 = op2.getNumerator(); de2 = op2.getDenominator(); double sh1 = nu1 / de1; double sh2 = nu2 / de2;
if
if (sh1 - sh2 >0.0001) return 1; else if (sh2 - sh1 > 0.0001) return -1; else return 0;
implements Comparable
public class RationalNumber implements Comparable
RationalNumber r8 = new RationalNumber(1, 1000000); RationalNumber r9 = new RationalNumber(2, 1000000); if (r8.compareTo(r9) == -1) System.out.println("r8 r9"); else System.out.println("r8 = r9");
==
=