定义一个复数类,完成复数的加法运算,并进行测试。要求:使用重载构造方法和setComplex方法,为变量成员赋值。例如:(1+2i)+(3+4i)=4+6i用java语句
时间: 2023-05-26 08:07:50 浏览: 87
public class ComplexNumber {
private double realPart;
private double imaginaryPart;
public ComplexNumber() {
this.realPart = 0;
this.imaginaryPart = 0;
}
public ComplexNumber(double realPart, double imaginaryPart) {
this.realPart = realPart;
this.imaginaryPart = imaginaryPart;
}
public void setComplexNumber(double realPart, double imaginaryPart) {
this.realPart = realPart;
this.imaginaryPart = imaginaryPart;
}
public double getRealPart() {
return realPart;
}
public double getImaginaryPart() {
return imaginaryPart;
}
public ComplexNumber add(ComplexNumber other) {
double realPart = this.realPart + other.realPart;
double imaginaryPart = this.imaginaryPart + other.imaginaryPart;
return new ComplexNumber(realPart, imaginaryPart);
}
}
// 测试代码
ComplexNumber complex1 = new ComplexNumber(1, 2);
ComplexNumber complex2 = new ComplexNumber(3, 4);
ComplexNumber sum = complex1.add(complex2);
System.out.println("(" + complex1.getRealPart() + " " + complex1.getImaginaryPart() + "i) + (" + complex2.getRealPart() + " " + complex2.getImaginaryPart() + "i) = " + sum.getRealPart() + " " + sum.getImaginaryPart() + "i"); // 输出:(1.0 2.0i) + (3.0 4.0i) = 4.0 6.0i
阅读全文