声明并测试一个复数类,其方法包括toString()以及复数的加减乘运算。
时间: 2024-05-11 19:15:20 浏览: 161
好的,这是一个关于编程的问题,很高兴回答。下面是一个Java语言的复数类,已经实现了toString()和复数的加减乘运算方法:
```
public class ComplexNumber {
private double real;
private double imaginary;
public ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
public String toString() {
return real + " + " + imaginary + "i";
}
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 ComplexNumber multiply(ComplexNumber other) {
double newReal = real * other.real - imaginary * other.imaginary;
double newImaginary = real * other.imaginary + imaginary * other.real;
return new ComplexNumber(newReal, newImaginary);
}
}
```
你可以通过创建一个ComplexNumber对象,并调用其方法来测试它的功能。
阅读全文