用Java声明并测试一个复数类,其方法包括 toString()及复数的加、减、乘运算
时间: 2024-06-12 21:09:05 浏览: 92
可以使用Java声明并测试一个复数类,如下所示:
```java
public class ComplexNumber {
private double real;
private double imaginary;
public ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
public String toString() {
if (imaginary < 0) {
return real + " - " + Math.abs(imaginary) + "i";
} else {
return real + " + " + imaginary + "i";
}
}
public ComplexNumber add(ComplexNumber other) {
double newReal = this.real + other.real;
double newImaginary = this.imaginary + other.imaginary;
return new ComplexNumber(newReal, newImaginary);
}
public ComplexNumber subtract(ComplexNumber other) {
double newReal = this.real - other.real;
double newImaginary = this.imaginary - other.imaginary;
return new ComplexNumber(newReal, newImaginary);
}
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);
}
}
```
使用上述复数类进行测试的示例代码如下:
```java
public class Main {
public static void main(String[] args) {
ComplexNumber num1 = new ComplexNumber(3, 2);
ComplexNumber num2 = new ComplexNumber(1, -1);
System.out.println("num1: " + num1.toString());
System.out.println("num2: " + num2.toString());
ComplexNumber sum = num1.add(num2);
ComplexNumber difference = num1.subtract(num2);
ComplexNumber product = num1.multiply(num2);
System.out.println("Sum: " + sum.toString());
System.out.println("Difference: " + difference.toString());
System.out.println("Product: " + product.toString());
}
}
```
输出结果:
```
num1: 3.0 + 2.0i
num2: 1.0 - 1.0i
Sum: 4.0 + 1.0i
Difference: 2.0 + 3.0i
Product: 5.0 + 1.0i
```
阅读全文