原文: https://beginnersbook.com/2018/09/java-program-to-add-two-complex-numbers/
复数有两部分 - 实部和虚部。在教程中,我们编写 Java 程序来相加两个复数。相加复数时,我们将实部和虚部加在一起,如下图所示。

示例 - 在 Java 中相加两个复数
在这个程序中,我们有一个类ComplexNumber。在这个类中,我们有两个实例变量real和img来保存复数的实部和虚部。
我们已经声明了一个方法sum(),通过将它们的实部和虚部加在一起来相加两个数字。
此类的构造函数用于初始化复数。对于例如当我们像这个ComplexNumber temp = new ComplexNumber(0, 0);创建这个类的实例时,它实际上会创建一个复数0 + 0i。
public class ComplexNumber{//for real and imaginary parts of complex numbersdouble real, img;//constructor to initialize the complex numberComplexNumber(double r, double i){this.real = r;this.img = i;}public static ComplexNumber sum(ComplexNumber c1, ComplexNumber c2){//creating a temporary complex number to hold the sum of two numbersComplexNumber temp = new ComplexNumber(0, 0);temp.real = c1.real + c2.real;temp.img = c1.img + c2.img;//returning the output complex numberreturn temp;}public static void main(String args[]) {ComplexNumber c1 = new ComplexNumber(5.5, 4);ComplexNumber c2 = new ComplexNumber(1.2, 3.5);ComplexNumber temp = sum(c1, c2);System.out.printf("Sum is: "+ temp.real+" + "+ temp.img +"i");}}
输出:
Sum is: 6.7 + 7.5i
屏幕截图:Eclipse IDE 中的相同 Java 程序 -

Eclipse IDE 中的输出:

以下是一些相关的 java 示例:
