java定义复数类实现复数的加减乘除运算
时间: 2023-05-23 19:05:14 浏览: 127
一个基本的Java定义复数类的示例如下所示,其中包括实部和虚部的私有变量,以及各种运算操作的公共方法:
```java
public class ComplexNumber {
private double realPart;
private double imaginaryPart;
public ComplexNumber(double realPart, double imaginaryPart) {
this.realPart = realPart;
this.imaginaryPart = imaginaryPart;
}
public ComplexNumber add(ComplexNumber other) {
double real = this.realPart + other.realPart;
double imaginary = this.imaginaryPart + other.imaginaryPart;
return new ComplexNumber(real, imaginary);
}
public ComplexNumber subtract(ComplexNumber other) {
double real = this.realPart - other.realPart;
double imaginary = this.imaginaryPart - other.imaginaryPart;
return new ComplexNumber(real, imaginary);
}
public ComplexNumber multiply(ComplexNumber other) {
double real = (this.realPart * other.realPart) - (this.imaginaryPart * other.imaginaryPart);
double imaginary = (this.realPart * other.imaginaryPart) + (this.imaginaryPart * other.realPart);
return new ComplexNumber(real, imaginary);
}
public ComplexNumber divide(ComplexNumber other) {
double denominator = (other.realPart * other.realPart) + (other.imaginaryPart * other.imaginaryPart);
double real = ((this.realPart * other.realPart) + (this.imaginaryPart * other.imaginaryPart)) / denominator;
double imaginary = ((this.imaginaryPart * other.realPart) - (this.realPart * other.imaginaryPart)) / denominator;
return new ComplexNumber(real, imaginary);
}
@Override
public String toString() {
if (this.imaginaryPart >= 0) {
return this.realPart + "+" + this.imaginaryPart + "i";
} else {
return this.realPart + "-" + (-this.imaginaryPart) + "i";
}
}
// getters and setters omitted for brevity
}
```
上面代码中实现了复数类的加减乘除运算,其中方法 ```add```,```subtract```,```multiply```和 ```divide``` 分别对应复数的加法,减法,乘法,除法。在乘法运算中实现了复数相乘的根据公式: $(a+bi)*(c+di)=(ac-bd)+(ad+bc)i$,在除法运算中实现了复数相乘公式的倒数。
```toString``` 方法重载了打印的字符串描述,使之可视化输出结果。该方法只是为了输出便于查看复数的操作结果,不是必需的方法。
阅读全文