用java求两个复数相加后的结果。 两个复数之间相加的运算法则:实部与实部相加,虚部与虚部相加
时间: 2024-05-21 21:11:12 浏览: 157
public class ComplexNumber {
private double realPart;
private double imaginaryPart;
public ComplexNumber(double realPart, double imaginaryPart) {
this.realPart = realPart;
this.imaginaryPart = imaginaryPart;
}
public ComplexNumber add(ComplexNumber other) {
double real = this.realPart + other.realPart;
double imaginary = this.imaginaryPart + other.imaginaryPart;
return new ComplexNumber(real, imaginary);
}
public String toString() {
return "(" + realPart + " + " + imaginaryPart + "i)";
}
}
// 在主函数中测试
public static void main(String[] args) {
ComplexNumber a = new ComplexNumber(3, 2);
ComplexNumber b = new ComplexNumber(1, 7);
ComplexNumber c = a.add(b);
System.out.println(c.toString());
}
// 输出结果为 (4.0 + 9.0i)
阅读全文