用Java编写程序:声明复数类Complex,成员变量包括实现由字符串构造复数,复数加法,减法,字符串描述,比较相等等操作
时间: 2024-10-19 22:13:50 浏览: 23
复数类的JAVA实现
3星 · 编辑精心推荐
在Java中,我们可以创建一个名为`Complex`的类来表示复数,并提供一些基本的操作。以下是一个简单的复数类的设计示例:
```java
public class Complex {
private double real; // 实部
private double imaginary; // 虚部
// 构造函数,接受字符串形式的复数(a + bi)
public Complex(String complexString) {
String[] parts = complexString.split(" ");
if (parts.length != 2) throw new IllegalArgumentException("Invalid format for complex number");
this.real = Double.parseDouble(parts[0]);
this.imaginary = Double.parseDouble(parts[1]);
}
// 加法方法
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 this.real + " + " + this.imaginary + "i";
}
// 比较两个复数是否相等
@Override
public boolean equals(Object obj) {
if (obj instanceof Complex) {
Complex c = (Complex) obj;
return this.real == c.real && this.imaginary == c.imaginary;
}
return false;
}
}
```
阅读全文