如何用Java编程实现复数类(ComplexNumber),并完成加法、减法、乘法和除法的运算方法?
时间: 2024-10-28 21:11:56 浏览: 36
复数(Complex Number)的四则运算.zip_Complex_number_四则运算_复数_复数运算
在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.getRealPart();
double newImag = this.imaginaryPart + other.getImaginaryPart();
return new ComplexNumber(newReal, newImag);
}
// 减法
public ComplexNumber subtract(ComplexNumber other) {
double newReal = this.realPart - other.getRealPart();
double newImag = this.imaginaryPart - other.getImaginaryPart();
return new ComplexNumber(newReal, newImag);
}
// 乘法
public ComplexNumber multiply(ComplexNumber other) {
double realProduct = this.realPart * other.getRealPart() - this.imaginaryPart * other.getImaginaryPart();
double imagProduct = this.realPart * other.getImaginaryPart() + this.imaginaryPart * other.getRealPart();
return new ComplexNumber(realProduct, imagProduct);
}
// 除法(假设除数非零)
public ComplexNumber divide(ComplexNumber divisor) {
double denominator = divisor.getRealPart() * divisor.getRealPart() + divisor.getImaginaryPart() * divisor.getImaginaryPart();
double realQuotient = (this.realPart * divisor.getRealPart() + this.imaginaryPart * divisor.getImaginaryPart()) / denominator;
double imagQuotient = (this.imaginaryPart * divisor.getRealPart() - this.realPart * divisor.getImaginaryPart()) / denominator;
return new ComplexNumber(realQuotient, imagQuotient);
}
}
```
现在你可以在其他类中实例化`ComplexNumber`对象,并使用这些方法来进行复数运算。例如:
```java
public static void main(String[] args) {
ComplexNumber c1 = new ComplexNumber(3, 4);
ComplexNumber c2 = new ComplexNumber(1, 2);
ComplexNumber sum = c1.add(c2); // 输出结果是 (4, 6)
System.out.println("Sum: " + sum.getRealPart() + ", " + sum.getImaginaryPart());
// ... 省略其他运算方法的示例
}
```
阅读全文