用Java编写一个`Complex`类,用于表示复数。该类需要实现: 构造函数:接收实部和虚部作为参数。 加法方法:实现两个复数相加的功能。 减法方法:实现两个复数相减的功能。
时间: 2024-09-27 18:07:12 浏览: 55
在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 double getReal() {
return real;
}
public void setReal(double real) {
this.real = real;
}
public double getImaginary() {
return imaginary;
}
public void setImaginary(double imaginary) {
this.imaginary = imaginary;
}
// 加法方法,两个复数相加
public Complex add(Complex other) {
double newReal = this.real + other.getReal();
double newImaginary = this.imaginary + other.getImaginary();
return new Complex(newReal, newImaginary);
}
// 减法方法,两个复数相减
public Complex subtract(Complex other) {
double newReal = this.real - other.getReal();
double newImaginary = this.imaginary - other.getImaginary();
return new Complex(newReal, newImaginary);
}
// 打印复数的格式(a+bi)
@Override
public String toString() {
return real + " + " + imaginary + "i";
}
}
```
现在你可以使用这个`Complex`类来创建复数对象并进行加减操作了。例如:
```java
Complex c1 = new Complex(2, 3);
Complex c2 = new Complex(4, -1);
Complex sum = c1.add(c2); // (2+3) + (4-1)i
System.out.println(sum); // 输出:6 + 2i
Complex difference = c1.subtract(c2); // (2+3) - (4-1)i
System.out.println(difference); // 输出:-2 + 4i
```
阅读全文