修改 RationalNumber 類,使其實現 Comparable 接口。爲了實現比較,首先計算兩個 RationalNumber 對象(分子和分母)的浮點數等價值,而後以0.0001爲偏差精度進行比較。編寫一個 main 驅動方法,測試你的修改結果。html
本題重點是實現 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 if (r8.compareTo(r9) == 1) System.out.println("r8 > r9"); else System.out.println("r8 = r9");
if
語句,不瞭解「是否相等」須要使用==
而使用了=
,編譯屢次錯誤。implements Comparable
,後來老師講到了,修改後沒有上傳碼雲。