设计一个复数类,实现两个复数相加减
时间: 2024-10-19 09:16:14 浏览: 26
设计一个复数类(ComplexNumber),首先需要包含两个私有成员变量:实部(real)和虚部(imaginary)。为了实现复数的加法和减法操作,我们可以创建公共方法:
```java
public class ComplexNumber {
private double real;
private double imaginary;
// 构造函数
public ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
// 实现复数相加
public ComplexNumber add(ComplexNumber other) {
double newReal = this.real + other.real;
double newImaginary = this.imaginary + other.imaginary;
return new ComplexNumber(newReal, newImaginary);
}
// 实现复数相减
public ComplexNumber subtract(ComplexNumber other) {
double newReal = this.real - other.real;
double newImaginary = this.imaginary - other.imaginary;
return new ComplexNumber(newReal, newImaginary);
}
// 返回字符串表示形式
@Override
public String toString() {
return "ComplexNumber{" +
"real=" + real +
", imaginary=" + imaginary +
'}';
}
}
```
在这个类中,我们通过`add()`和`subtract()`方法接受另一个复数作为参数,并计算出结果的新复数。每个方法内部处理了实部和虚部的加减运算。
你可以这样使用这个类:
```java
public static void main(String[] args) {
ComplexNumber num1 = new ComplexNumber(2, 3);
ComplexNumber num2 = new ComplexNumber(4, -5);
ComplexNumber sum = num1.add(num2);
System.out.println("Sum: " + sum); // 输出:Sum: ComplexNumber{real=6, imaginary=-2}
ComplexNumber difference = num1.subtract(num2);
System.out.println("Difference: " + difference); // 输出:Difference: ComplexNumber{real=-2, imaginary=8}
}
```
阅读全文