1、调试通过:(1)复数类。编写一个类实现复数的运算。要求至少实现复数相加、复数相减、复数相乘等功能。
时间: 2024-10-24 08:06:22 浏览: 23
在Java中创建一个复数类,用于支持复数的加法、减法和乘法操作,你可以按照以下步骤实现:
```java
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) {
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);
}
// 返回字符串表示形式
@Override
public String toString() {
return "(" + real + " + " + imaginary + "i)";
}
}
// 示例
public static void main(String[] args) {
ComplexNumber c1 = new ComplexNumber(3, 4);
ComplexNumber c2 = new ComplexNumber(-2, 5);
ComplexNumber sum = c1.add(c2);
System.out.println("Sum: " + sum); // 输出结果类似 (1 + 9i)
ComplexNumber diff = c1.subtract(c2);
System.out.println("Difference: " + diff); // 输出结果类似 (5 - 1i)
ComplexNumber product = c1.multiply(c2);
System.out.println("Product: " + product); // 输出结果类似 (-6 + 7i)
}
```
阅读全文