用Java实现声明复数类Complex,成员变量包括实部和虚部,成员方法包括实现由字符串构造复数、复数加法、减法、字符串描述、比较相等、计算复数的模√(实部²+虚部²)等操作。
时间: 2024-10-08 08:03:42 浏览: 48
在Java中,我们可以创建一个名为`Complex`的类来表示复数,它有两个私有成员变量`real`和`imaginary`分别代表实部和虚部。以下是一个简单的实现:
```java
public class Complex {
private double real;
private double imaginary;
// 构造函数,接受字符串解析复数
public Complex(String complexString) {
String[] parts = complexString.split(" ");
if (parts.length == 2) {
this.real = Double.parseDouble(parts[0]);
this.imaginary = Double.parseDouble(parts[1]);
} else {
throw new IllegalArgumentException("Invalid complex number format");
}
}
// 复数加法
public Complex add(Complex other) {
return new Complex(this.real + other.real, this.imaginary + other.imaginary);
}
// 减法
public Complex subtract(Complex other) {
return new Complex(this.real - other.real, this.imaginary - other.imaginary);
}
// 返回字符串描述
@Override
public String toString() {
return "Complex{" +
"real=" + real +
", imaginary=" + imaginary +
'}';
}
// 比较相等
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Complex complex = (Complex) obj;
return Double.compare(real, complex.real) == 0 &&
Double.compare(imaginary, complex.imaginary) == 0;
}
// 计算复数模
public double magnitude() {
return Math.sqrt(Math.pow(real, 2) + Math.pow(imaginary, 2));
}
// 其他方法...
}
```
阅读全文