编写一个名为“复数”的类,包含复数的实部和虚部(数据成员),以及复数之间的基本算术运算:加、减(方法成员),并要求复数加减运算,程序运行中能对给定的复数进行运算,并打印运算的结果。
时间: 2024-03-21 09:42:01 浏览: 98
下面是一个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 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 String toString() {
return "(" + this.real + " + " + this.imaginary + "i)";
}
public static void main(String[] args) {
ComplexNumber c1 = new ComplexNumber(2, 3);
ComplexNumber c2 = new ComplexNumber(4, -5);
ComplexNumber sum = c1.add(c2);
ComplexNumber difference = c1.subtract(c2);
System.out.println(c1 + " + " + c2 + " = " + sum);
System.out.println(c1 + " - " + c2 + " = " + difference);
}
}
```
在这个示例中,我们首先定义了一个名为ComplexNumber的类,其中包含实部和虚部作为数据成员,并且实现了add和subtract方法来实现复数的加法和减法。我们还实现了toString方法,以便在输出时能够更好地理解复数的值。
在main方法中,我们创建了两个ComplexNumber对象c1和c2,并使用它们调用add和subtract方法。然后我们打印了每个运算的结果,以便能够查看它们是否正确。
阅读全文