复数相加减 1)声明一个复数类 Complex,定义方法add将当前复数对象和参数指定的复数对象相加得到一个新的复数。定义方法subtract将当前复数对象和参数指定的复数对象相减得到一个新的复数。 (2)编写程序测试Complex类。要求测试的输出结果为: (6+8i)+(10+12i)=(16+20i) (6+8i)-(10+12i)=(-4-4i) (6+8i)+(6+8i)=(12+16i)
时间: 2024-03-16 16:43:07 浏览: 72
以下是实现复数相加减操作的Complex类的代码:
```
public class Complex {
private double real; // 复数的实部
private double imag; // 复数的虚部
// 构造函数
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
// 复数相加
public Complex add(Complex c) {
double newReal = this.real + c.real;
double newImag = this.imag + c.imag;
return new Complex(newReal, newImag);
}
// 复数相减
public Complex subtract(Complex c) {
double newReal = this.real - c.real;
double newImag = this.imag - c.imag;
return new Complex(newReal, newImag);
}
// 输出复数的字符串表示
public String toString() {
return "(" + this.real + "+" + this.imag + "i)";
}
}
```
然后,我们可以编写一个测试程序来测试Complex类的add和subtract方法:
```
public class TestComplex {
public static void main(String[] args) {
Complex c1 = new Complex(6, 8);
Complex c2 = new Complex(10, 12);
Complex c3 = c1.add(c2);
Complex c4 = c1.subtract(c2);
Complex c5 = c1.add(c1);
System.out.println(c1.toString() + "+" + c2.toString() + "=" + c3.toString());
System.out.println(c1.toString() + "-" + c2.toString() + "=" + c4.toString());
System.out.println(c1.toString() + "+" + c1.toString() + "=" + c5.toString());
}
}
```
运行以上程序,输出结果为:
```
(6.0+8.0i)+(10.0+12.0i)=(16.0+20.0i)
(6.0+8.0i)-(10.0+12.0i)=(-4.0-4.0i)
(6.0+8.0i)+(6.0+8.0i)=(12.0+16.0i)
```
可以看到,测试结果符合预期。
阅读全文