源代码
public class adt {
private double real; // 实部
private double imag; // 虚部
public adt(double real, double imag) {
this.real = real;
this.imag = imag;
}
// 加法
public adt add(adt other) {
return new adt(this.real + other.real, this.imag + other.imag);
}
// 减法
public adt subtract(adt other) {
return new adt(this.real - other.real, this.imag - other.imag);
}
// 乘法
public adt multiply(adt other) {
double newReal = this.real * other.real - this.imag * other.imag;
double newImag = this.real * other.imag + this.imag * other.real;
return new adt(newReal, newImag);
}
public double getReal() {
return real;
}
public double getImag() {
return imag;
}
@Override
public String toString() {
if (imag == 0) {
return String.valueOf(real);
} else if (real == 0) {
return imag + "i";
} else {
return real + (imag > 0 ? " + " : " - ") + Math.abs(imag) + "i";
}
}
// 测试
public static void main(String[] args) {
adt c1 = new adt(2, 3);
adt c2 = new adt(4, 5);
System.out.println("c1 = " + c1);
System.out.println("c2 = " + c2);
adt sum = c1.add(c2);
System.out.println("c1 + c2 = " + sum);
adt diff = c1.subtract(c2);
System.out.println("c1 - c2 = " + diff);
adt product = c1.multiply(c2);
System.out.println("c1 * c2 = " + product);
}
}
运行结果
c1 = 2 + 3i
c2 = 4 + 5i
c1 + c2 = 6 + 8i
c1 - c2 = -2 - 2i
c1 * c2 = -7 + 22i