JAVA-有理數類
阿新 • • 發佈:2021-09-27
有理數類
類的成員變數
任何一個有理數都可以用分數進行表示,所以有理數類的成員應該包含兩個:
int numerator = 1;//分子
int denominator = 1;//分母
無參構造與傳參構造
public Rational() {
}
;//無參構造
public Rational(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
get set 函式
public int getNumerator() { return numerator; } public int getDenominator() { return denominator; } public void setNumerator(int numerator) { this.numerator = numerator; } public void setDenominator(int denominator) { this.denominator = denominator; }
類的方法
有理數重要的運算:四則運算
//四則運算 Rational add(Rational a) { Rational c = new Rational(); c.denominator = this.denominator * a.denominator; c.numerator = this.denominator * a.numerator + this.numerator * a.denominator; return c; } Rational sub(Rational a) { Rational c = new Rational(); c.denominator = this.denominator * a.denominator; c.numerator = this.denominator * a.numerator - this.numerator * a.denominator; return c; } Rational mult(Rational a) { Rational c = new Rational(); c.denominator = this.denominator * a.denominator; c.numerator = this.numerator * a.numerator; return c; } Rational div(Rational a) { Rational c = new Rational(); c.denominator = this.denominator * a.denominator; c.numerator = this.numerator * a.denominator; return c; } public String toString() { return ("分母是:" + numerator + " 分子是:" + denominator); }
轉化位小數方法
//得值
public double doubleVaule() {
return numerator * 1.0 / denominator * 1.0;
}
equals比較方法
public boolean equals(Rational a) { if ((a.getDenominator() == this.denominator) && (a.getNumerator() == this.numerator)) return true; else return false; } }
列印分母、分子的值
public String toString() {
return ("分母是:" + numerator + " 分子是:" + denominator);
}
測試分析
Test進行測試
public class Test {
public static void main(String[] args) {
Rational r =new Rational(3,4);
Rational r2=new Rational(1,2);
System.out.println(r.add(r2));
System.out.println(r.div(r2));
System.out.println(r.mult(r2));
System.out.println(r.sub(r2));
System.out.println(r.equals(r2));
System.out.println(r.doubleVaule());
System.out.println(r2.doubleVaule());
System.out.println(r);
System.out.println(r2);
}
}