java创建一个复数类
时间: 2023-11-10 18:55:49 浏览: 43
好的,关于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 sub(Complex other) {
return new Complex(this.real - other.real, this.imag - other.imag);
}
public Complex mult(Complex other) {
double real = this.real * other.real - this.imag * other.imag;
double imag = this.real * other.imag + this.imag * other.real;
return new Complex(real, imag);
}
public Complex div(Complex other) {
double denom = other.real * other.real + other.imag * other.imag;
double real = (this.real * other.real + this.imag * other.imag) / denom;
double imag = (this.imag * other.real - this.real * other.imag) / denom;
return new Complex(real, imag);
}
@Override
public String toString() {
return this.real + " + " + this.imag + "i";
}
}
以上是一个简单的复数类的实现,您可以在实际应用中根据需要进行修改和扩展。