要實現一個Java復數類,你可以按照以下步驟進行:
public class Complex {
private double real;
private double imaginary;
// 構造方法、getter和setter等其他方法
}
public Complex(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
public double getReal() {
return real;
}
public void setReal(double real) {
this.real = real;
}
public double getImaginary() {
return imaginary;
}
public void setImaginary(double imaginary) {
this.imaginary = imaginary;
}
實現復數加法和乘法的方法。可以使用以下公式計算兩個復數的和和積:
public Complex add(Complex other) {
double realPart = this.real + other.real;
double imaginaryPart = this.imaginary + other.imaginary;
return new Complex(realPart, imaginaryPart);
}
public Complex multiply(Complex other) {
double realPart = this.real * other.real - this.imaginary * other.imaginary;
double imaginaryPart = this.real * other.imaginary + this.imaginary * other.real;
return new Complex(realPart, imaginaryPart);
}
@Override
public String toString() {
if (imaginary >= 0) {
return real + " + " + imaginary + "i";
} else {
return real + " - " + (-imaginary) + "i";
}
}
這樣,你就可以使用這個Complex類來表示和操作復數了。例如:
Complex a = new Complex(2, 3);
Complex b = new Complex(4, -1);
Complex sum = a.add(b);
System.out.println("Sum: " + sum);
Complex product = a.multiply(b);
System.out.println("Product: " + product);
輸出結果為:
Sum: 6.0 + 2.0i
Product: 11.0 + 10.0i