用Java定义一个复数类,完成复数的加法运算,并进行测试。要求:使用重载构造方法和setComplex方法,为变量成员赋值。
时间: 2023-05-23 07:02:47 浏览: 108
非常感谢您的提问!以下是复数类的实现示例:
```java
public class Complex {
private double real;
private double imaginary;
public Complex() {
this.real = 0;
this.imaginary = 0;
}
public Complex(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
public Complex(Complex c) {
this.real = c.real;
this.imaginary = c.imaginary;
}
public void setComplex(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
public Complex add(Complex c) {
return new Complex(this.real + c.real, this.imaginary + c.imaginary);
}
@Override
public String toString() {
return this.real + (this.imaginary < 0 ? "" : "+") + this.imaginary + "i";
}
}
```
接下来是测试代码:
```java
public static void main(String[] args) {
Complex c1 = new Complex(1, 2);
Complex c2 = new Complex(3, -4);
Complex c3 = c1.add(c2);
System.out.println(c1); // 1.0+2.0i
System.out.println(c2); // 3.0-4.0i
System.out.println(c3); // 4.0-2.0i
}
```
上述代码实现了一个复数类,其中包含了构造方法、setComplex方法和add方法,用于创建复数对象并进行加法运算。测试代码演示了如何使用这些方法来操作复数,并输出运算结果。希望这个示例能够帮助您!
阅读全文