java定义一个复数类complex
时间: 2023-06-05 07:47:24 浏览: 163
```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 void setReal(double real) {
this.real = real;
}
public double getImag() {
return imag;
}
public void setImag(double imag) {
this.imag = imag;
}
public Complex add(Complex c) {
return new Complex(real + c.real, imag + c.imag);
}
public Complex subtract(Complex c) {
return new Complex(real - c.real, imag - c.imag);
}
public Complex multiply(Complex c) {
return new Complex(real*c.real - imag*c.imag, real*c.imag + imag*c.real);
}
public Complex divide(Complex c) {
double a = real, b = imag, c = c.real, d = c.imag;
return new Complex((a*c + b*d) / (c*c + d*d), (b*c - a*d) / (c*c + d*d));
}
public String toString() {
return "(" + real + " + " + imag + "i)";
}
}
```
这是一个简单的复数类的实现,它包含了常见的加减乘除方法,以及用于获取实部和虚部的 get 方法和 set 方法。请注意,这里的复数是用实部和虚部来表示的。
相关推荐
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)