java声明并测试一个复数类,其方法包括 toString()及复数的加、减、乘运算。并将代码补充在右侧编辑器中。
时间: 2024-06-12 17:09:05 浏览: 190
下面是一个用Java声明并测试一个复数类的示例代码,其中包括了toString()方法和复数的加、减、乘运算:
```
public class ComplexNumber {
private double real;
private double imaginary;
public ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
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);
}
public ComplexNumber multiply(ComplexNumber other) {
double newReal = this.real * other.real - this.imaginary * other.imaginary;
double newImaginary = this.real * other.imaginary + this.imaginary * other.real;
return new ComplexNumber(newReal, newImaginary);
}
@Override
public String toString() {
return "(" + real + " + " + imaginary + "i)";
}
}
public class Main {
public static void main(String[] args) {
ComplexNumber t1 = new ComplexNumber(3, 4);
ComplexNumber t2 = new ComplexNumber(2, -1);
System.out.println("(a + b) = " + t1.add(t2).toString());
System.out.println("(a - b) = " + t1.subtract(t2).toString());
System.out.println("(a * b) = " + t1.multiply(t2).toString());
}
}
```
阅读全文