代码如下:
//编写复数类,实现复数相加和相减
public class ComplexNumber {
private double a;//实部
private double b;//虚部
public ComplexNumber(double a, double b) {
this.a = a;
this.b = b;
}
public ComplexNumber add(ComplexNumber cn) {
this.a += cn.a;
this.b += cn.b;
return this;//this代表调用该方法的对象
//将两个复数相加的结果保存在被加的复数对象中
}
public ComplexNumber sub(ComplexNumber cn) {
this.a -= cn.a;
this.b -= cn.b;
return this;
}
public static void main(String[] args) {
ComplexNumber cn1 = new ComplexNumber(1, 2);
ComplexNumber cn2 = new ComplexNumber(3, 4);
System.out.println("未进行任何操作时,复数cn1为:" + cn1.a + "+" + cn1.b + "i");
System.out.println("未进行任何操作时,复数cn2为:" + cn2.a + "+" + cn2.b + "i");
cn1.add(cn2);
System.out.println("执行复数相加操作之后,复数cn1为:" + cn1.a + "+" + cn1.b + "i");
System.out.println("执行复数相加操作之后,复数cn2为:" + cn2.a + "+" + cn2.b + "i");
cn1.sub(cn2);
System.out.println("执行复数相减操作之后,复数cn1为:" + cn1.a + "+" + cn1.b + "i");
System.out.println("执行复数相减操作之后,复数cn2为:" + cn2.a + "+" + cn2.b + "i");
}
}
运行结果: