要实现一个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