有理數是整數、分數的統稱。在Java中設計和實現有理數可以采用類的方式,一個有理數類應該含有以下屬性和方法:
public class RationalNumber { private int numerator; // 分子 private int denominator; // 分母 public RationalNumber(int numerator, int denominator) { this.numerator = numerator; this.denominator = denominator; } public int getNumerator() { return numerator; } public int getDenominator() { return denominator; } public RationalNumber add(RationalNumber number) { int newNumerator = numerator * number.getDenominator() + number.getNumerator() * denominator; int newDenominator = denominator * number.getDenominator(); return new RationalNumber(newNumerator, newDenominator); } public RationalNumber subtract(RationalNumber number) { int newNumerator = numerator * number.getDenominator() - number.getNumerator() * denominator; int newDenominator = denominator * number.getDenominator(); return new RationalNumber(newNumerator, newDenominator); } public RationalNumber multiply(RationalNumber number) { int newNumerator = numerator * number.getNumerator(); int newDenominator = denominator * number.getDenominator(); return new RationalNumber(newNumerator, newDenominator); } public RationalNumber divide(RationalNumber number) { int newNumerator = numerator * number.getDenominator(); int newDenominator = denominator * number.getNumerator(); return new RationalNumber(newNumerator, newDenominator); } public String toString() { return numerator + "/" + denominator; } }
在上面的代碼中,我們定義了有理數的分子和分母屬性,并且提供了加、減、乘、除四個操作的方法。在加減乘除時,需要注意分母的乘法操作和約分操作。同時,我們還定義了toString方法,用于將有理數轉換成字符串。
使用該有理數類,示例如下:
RationalNumber a = new RationalNumber(1, 2); RationalNumber b = new RationalNumber(2, 3); RationalNumber c = a.add(b); RationalNumber d = a.subtract(b); RationalNumber e = a.multiply(b); RationalNumber f = a.divide(b); System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("a + b = " + c); System.out.println("a - b = " + d); System.out.println("a * b = " + e); System.out.println("a / b = " + f);
運行結果如下:
a = 1/2 b = 2/3 a + b = 7/6 a - b = -1/6 a * b = 1/3 a / b = 3/4
以上示例展示了有理數的加減乘除操作,并且輸出了結果。
下一篇css塊元素上移