原文: https://www.programiz.com/java-programming/examples/add-complex-number
public class Complex {
double real;
double imag;
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
public static void main(String[] args) {
Complex n1 = new Complex(2.3, 4.5),
n2 = new Complex(3.4, 5.0),
temp;
temp = add(n1, n2);
System.out.printf("Sum = %.1f + %.1fi", temp.real, temp.imag);
}
public static Complex add(Complex n1, Complex n2)
{
Complex temp = new Complex(0.0, 0.0);
temp.real = n1.real + n2.real;
temp.imag = n1.imag + n2.imag;
return(temp);
}
}运行该程序时,输出为:
Sum = 5.7 + 9.5i在上面的程序中,我们创建了一个具有两个成员变量的类Complex:real和imag。 顾名思义,real存储复数的实数部分,imag存储虚数部分。
Complex类具有一个构造器,用于初始化real和imag的值。
我们还创建了一个新的静态函数add(),该函数将两个复数作为参数并将结果作为复数返回。
在add()方法内部,我们只添加复数n1和n2的实部和虚部,将其存储在新变量temp中,然后返回[ temp。
然后,在调用函数main()中,我们使用printf()函数进行打印。