以下是在 ComplexTest.java 中使用 division() 方法計算複數 (2, 2) 的倒數,並列印有意義的訊息:
首先,假設 Complex.java 已經包含了 division 方法,如前所述。
ComplexTest.java
java
複製程式碼
public class ComplexTest {
public static void main(String[] args) {
Complex y = new Complex(2.0, 2.0);
Complex one = new Complex(1.0, 0.0);
// 計算 y 的倒數
Complex yInverse = one.division(y);
// 列印出結果
System.out.println("The inverse of y (2, 2) is: " + yInverse);
// 驗證 yInverse * y 是否等於 1
Complex verification = yInverse.mul(y);
System.out.println("Verification (yInverse * y): " + verification);
}
}
Complex.java
假設 Complex.java 已包含以下方法:
java
複製程式碼
public class Complex {
private double real;
private double imag;
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
public Complex add(Complex other) {
return new Complex(this.real + other.real, this.imag + other.imag);
}
public Complex division(Complex right) {
double denominator = right.real * right.real + right.imag * right.imag;
double realPart = (this.real * right.real + this.imag * right.imag) / denominator;
double imagPart = (this.imag * right.real - this.real * right.imag) / denominator;
return new Complex(realPart, imagPart);
}
public Complex mul(Complex other) {
double realPart = this.real * other.real - this.imag * other.imag;
double imagPart = this.real * other.imag + this.imag * other.real;
return new Complex(realPart, imagPart);
}
@Override
public String toString() {
return "(" + this.real + ", " + this.imag + ")";
}
}
解釋
計算倒數:在 ComplexTest.java 中,我們創建了一個表示 1 的複數,然後用它來除以 y,計算 y 的倒數。
列印結果:我們列印出 y 的倒數,並通過計算 yInverse * y 來驗證結果是否等於 1。