java创建一个复数类
时间: 2023-10-22 13:32:32 浏览: 101
好的,很高兴为您解答。在 Java 中,可以通过定义一个类来创建复数。下面是一个示例代码:
class Complex {
private double real;
private double imaginary;
public Complex(double real, double imaginary) {
this.real = real;
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 subtract(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);
}
public String toString() {
return "(" + this.real + ", " + this.imaginary + "i)";
}
}
这个示例代码定义了一个名为 Complex 的类,它具有私有实部和虚部字段。它还具有三个方法,用于执行相加、相减和相乘操作。最后,它具有一个 toString() 方法,用于将复数对象转换为字符串。
希望这个答案能够解决您的问题。
阅读全文