java复数类总计
时间: 2023-10-11 10:16:57 浏览: 71
Java复数类
以下是一个简单的 Java 复数类:
```
public class Complex {
private double real;
private double imag;
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
public double getReal() {
return real;
}
public double getImag() {
return imag;
}
public Complex add(Complex other) {
double newReal = this.real + other.real;
double newImag = this.imag + other.imag;
return new Complex(newReal, newImag);
}
public Complex subtract(Complex other) {
double newReal = this.real - other.real;
double newImag = this.imag - other.imag;
return new Complex(newReal, newImag);
}
public Complex multiply(Complex other) {
double newReal = this.real * other.real - this.imag * other.imag;
double newImag = this.real * other.imag + this.imag * other.real;
return new Complex(newReal, newImag);
}
public Complex divide(Complex other) {
double denominator = other.real * other.real + other.imag * other.imag;
double newReal = (this.real * other.real + this.imag * other.imag) / denominator;
double newImag = (this.imag * other.real - this.real * other.imag) / denominator;
return new Complex(newReal, newImag);
}
public String toString() {
return real + " + " + imag + "i";
}
}
```
这个类包含了基本的复数运算:加、减、乘、除。可以通过创建新的 `Complex` 对象来表示结果。同时,这个类也包含了获取实部和虚部的方法,以及重写了 `toString()` 方法。
阅读全文