java 定义和实现复数类,使其完成复数的加减乘除及输出
时间: 2024-10-12 17:11:02 浏览: 37
在Java中定义和实现复数类,通常我们会创建一个名为`ComplexNumber`的类,它包含两个私有成员变量:实部(realPart)和虚部(imaginaryPart)。下面是一个简单的复数类的定义和实现:
```java
public class ComplexNumber {
private double realPart;
private double imaginaryPart;
// 构造函数
public ComplexNumber(double real, double imag) {
this.realPart = real;
this.imaginaryPart = imag;
}
// 获取和设置方法
public double getRealPart() {
return realPart;
}
public void setRealPart(double real) {
this.realPart = real;
}
public double getImaginaryPart() {
return imaginaryPart;
}
public void setImaginaryPart(double imag) {
this.imaginaryPart = imag;
}
// 复数运算方法:加法、减法、乘法和除法
public ComplexNumber add(ComplexNumber other) {
double newReal = this.realPart + other.realPart;
double newImag = this.imaginaryPart + other.imaginaryPart;
return new ComplexNumber(newReal, newImag);
}
public ComplexNumber subtract(ComplexNumber other) {
double newReal = this.realPart - other.realPart;
double newImag = this.imaginaryPart - other.imaginaryPart;
return new ComplexNumber(newReal, newImag);
}
public ComplexNumber multiply(ComplexNumber other) {
double newReal = this.realPart * other.realPart - this.imaginaryPart * other.imaginaryPart;
double newImag = this.realPart * other.imaginaryPart + this.imaginaryPart * other.realPart;
return new ComplexNumber(newReal, newImag);
}
// Java的复数除法涉及分母的共轭,这里假设除数不为零
public ComplexNumber divide(ComplexNumber divisor) {
double denominatorSquare = divisor.realPart * divisor.realPart + divisor.imaginaryPart * divisor.imaginaryPart;
double newReal = (this.realPart * divisor.realPart + this.imaginaryPart * divisor.imaginaryPart) / denominatorSquare;
double newImag = (this.imaginaryPart * divisor.realPart - this.realPart * divisor.imaginaryPart) / denominatorSquare;
return new ComplexNumber(newReal, newImag);
}
// 输出复数
@Override
public String toString() {
if (imaginaryPart >= 0) {
return "(" + realPart + " + " + imaginaryPart + "i)";
} else {
return "(" + realPart + " - " + Math.abs(imaginaryPart) + "i)";
}
}
}
```
阅读全文