声明并测试一个复数类,其方法包括 toString()及复数的加、减、乘运算。
时间: 2024-04-30 11:17:35 浏览: 23
以下是一个简单的复数类的实现,包括toString()及复数的加、减、乘运算:
```java
public class ComplexNumber {
private double real;
private double imaginary;
public ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
public double getReal() {
return real;
}
public double getImaginary() {
return imaginary;
}
public ComplexNumber add(ComplexNumber other) {
double realPart = this.real + other.real;
double imaginaryPart = this.imaginary + other.imaginary;
return new ComplexNumber(realPart, imaginaryPart);
}
public ComplexNumber subtract(ComplexNumber other) {
double realPart = this.real - other.real;
double imaginaryPart = this.imaginary - other.imaginary;
return new ComplexNumber(realPart, imaginaryPart);
}
public ComplexNumber multiply(ComplexNumber other) {
double realPart = this.real * other.real - this.imaginary * other.imaginary;
double imaginaryPart = this.real * other.imaginary + this.imaginary * other.real;
return new ComplexNumber(realPart, imaginaryPart);
}
@Override
public String toString() {
if (imaginary >= 0) {
return real + "+" + imaginary + "i";
} else {
return real + "" + imaginary + "i";
}
}
}
```
在该类中,我们定义了一个构造函数用于初始化实部和虚部,同时定义了getter方法,用于获取实部和虚部的值。此外,我们还实现了加、减、乘运算,每个操作都返回一个新的复数对象,以避免修改原始对象。
最后,我们通过覆盖toString()方法,以便在打印复数时能够打印出其实际值。这里的实现是将实部和虚部分别用加号或减号连接起来,如果虚部为负数,则省略中间的加号。
我们可以编写以下测试代码来测试该类的功能:
```java
public class Main {
public static void main(String[] args) {
ComplexNumber c1 = new ComplexNumber(2, 3);
ComplexNumber c2 = new ComplexNumber(4, -1);
System.out.println(c1.add(c2)); // 输出:6+2i
System.out.println(c1.subtract(c2)); // 输出:-2+4i
System.out.println(c1.multiply(c2)); // 输出:11+10i
}
}
```
在这个示例中,我们创建了两个复数对象,并分别进行了加、减、乘运算。在每个运算中,我们打印出结果,以确保它们是正确的。