声明复数类,成员变量包括实部和虚部,成员方法包括实现由字符串构造复数、复数加法、减法,字符串描述、比较相等,计算复数的模等操作
时间: 2024-10-14 19:15:14 浏览: 29
C++复数类实部和虚部
声明一个复数类,可以按照以下方式设计:
```java
public class ComplexNumber {
private double real; // 实部
private double imaginary; // 虚部
// 构造函数,通过字符串初始化复数
public ComplexNumber(String complexString) {
String[] parts = complexString.split(" + i\\b"); // 分割实部和虚部
if (parts.length == 2) {
this.real = Double.parseDouble(parts[0]);
this.imaginary = Double.parseDouble(parts[1]);
} else if (complexString.endsWith("i")) {
this.real = 0;
this.imaginary = Double.parseDouble(complexString.substring(0, complexString.length() - 1));
} else {
throw new IllegalArgumentException("Invalid complex number format");
}
}
// 复数加法
public ComplexNumber add(ComplexNumber other) {
return new ComplexNumber(this.real + other.real, this.imaginary + other.imaginary);
}
// 减法
public ComplexNumber subtract(ComplexNumber other) {
return new ComplexNumber(this.real - other.real, this.imaginary - other.imaginary);
}
// 字符串描述
@Override
public String toString() {
return real + " + " + imaginary + "i";
}
// 比较相等
@Override
public boolean equals(Object obj) {
if (obj instanceof ComplexNumber) {
ComplexNumber other = (ComplexNumber) obj;
return this.real == other.real && this.imaginary == other.imaginary;
}
return false;
}
// 计算复数的模
public double magnitude() {
return Math.sqrt(real * real + imaginary * imaginary);
}
}
```
阅读全文