java设计复数类,成员变量包括实部和虚部,成员方法包括实现复数加法、减法、比较、字符串描述、比较是否相等等操作
时间: 2023-07-10 08:11:47 浏览: 43
好的,我可以为您提供一个Java复数类的代码示例:
```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) {
return new ComplexNumber(real + other.real, imaginary + other.imaginary);
}
public ComplexNumber subtract(ComplexNumber other) {
return new ComplexNumber(real - other.real, imaginary - other.imaginary);
}
public boolean equals(ComplexNumber other) {
return (real == other.real && imaginary == other.imaginary);
}
public int compareTo(ComplexNumber other) {
if (real == other.real && imaginary == other.imaginary) {
return 0;
} else if (real > other.real || (real == other.real && imaginary > other.imaginary)) {
return 1;
} else {
return -1;
}
}
@Override
public String toString() {
return real + (imaginary >= 0 ? "+" : "-") + Math.abs(imaginary) + "i";
}
}
```
在这个代码示例中,我们定义了一个复数类`ComplexNumber`,包含了实部`real`和虚部`imaginary`两个成员变量。我们还定义了`add`和`subtract`方法分别实现复数的加法和减法,使用`equals`方法比较两个复数是否相等,使用`compareTo`方法比较两个复数的大小关系,使用`toString`方法返回复数的字符串描述。