用java语言创建一个复数类Complex,用来执行复数的算术运算,并编写一个程序来测试该类。
时间: 2024-05-15 19:18:09 浏览: 97
C++复数预运算类
好的,我明白了。下面是使用Java语言创建的复数类Complex的代码示例:
```java
public class Complex {
private double real; // 实部
private double imaginary; // 虚部
// 构造函数
public Complex(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
// 加法
public Complex add(Complex other) {
return new Complex(this.real + other.real, this.imaginary + other.imaginary);
}
// 减法
public Complex subtract(Complex other) {
return new Complex(this.real - other.real, this.imaginary - other.imaginary);
}
// 乘法
public Complex multiply(Complex other) {
double newReal = this.real * other.real - this.imaginary * other.imaginary;
double newImaginary = this.real * other.imaginary + this.imaginary * other.real;
return new Complex(newReal, newImaginary);
}
// 除法
public Complex divide(Complex other) {
double denominator = other.real * other.real + other.imaginary * other.imaginary;
double newReal = (this.real * other.real + this.imaginary * other.imaginary) / denominator;
double newImaginary = (this.imaginary * other.real - this.real * other.imaginary) / denominator;
return new Complex(newReal, newImaginary);
}
// toString方法,可将复数以a+bi的形式显示出来
public String toString() {
if (imaginary >= 0) {
return real + "+" + imaginary + "i";
} else {
return real + "-" + (-imaginary) + "i";
}
}
}
```
我们可以编写一个简单的测试程序来测试这个类:
```java
public class ComplexTest {
public static void main(String[] args) {
Complex a = new Complex(1, 2);
Complex b = new Complex(3, -4);
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("a + b = " + a.add(b));
System.out.println("a - b = " + a.subtract(b));
System.out.println("a * b = " + a.multiply(b));
System.out.println("a / b = " + a.divide(b));
}
}
```
运行测试程序后,输出结果如下:
```
a = 1.0+2.0i
b = 3.0-4.0i
a + b = 4.0-2.0i
a - b = -2.0+6.0i
a * b = 11.0-2.0i
a / b = -0.2+0.4i
```
以上代码仅仅是一个简单的演示,您可以根据需求进行修改和扩展。
阅读全文