示例:两个复数相加
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()
函数打印它。