企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# Java 程序:相加两个复数 > 原文: [https://beginnersbook.com/2018/09/java-program-to-add-two-complex-numbers/](https://beginnersbook.com/2018/09/java-program-to-add-two-complex-numbers/) **复数**有两部分 - 实部​​和虚部。在[教程](https://beginnersbook.com/java-tutorial-for-beginners-with-examples/)中,我们编写 [Java 程序](https://beginnersbook.com/2017/09/java-examples/)来**相加两个复数**。相加复数时,我们将实部和虚部加在一起,如下图所示。 ![Java Add two complex numbers](https://img.kancloud.cn/dd/bc/ddbc8d1b17cf1be49b0d2c7cd3a27d8c_600x249.jpg) ## 示例 - 在 Java 中相加两个复数 在这个程序中,我们有一个类`ComplexNumber`。在这个类中,我们有两个实例变量`real`和`img`来保存复数的实部和虚部。 我们已经声明了一个方法`sum()`,[通过将它们的实部和虚部加在一起来相加两个数字](https://beginnersbook.com/2017/09/java-program-to-add-two-numbers/)。 此类的构造函数用于初始化复数。对于例如当我们像这个`ComplexNumber temp = new ComplexNumber(0, 0);`创建这个类的实例时,它实际上会创建一个复数`0 + 0i`。 ```java public class ComplexNumber{ //for real and imaginary parts of complex numbers double real, img; //constructor to initialize the complex number ComplexNumber(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 numbers ComplexNumber temp = new ComplexNumber(0, 0); temp.real = c1.real + c2.real; temp.img = c1.img + c2.img; //returning the output complex number return 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"); } } ``` **输出:** ```java Sum is: 6.7 + 7.5i ``` 屏幕截图:Eclipse IDE 中的相同 Java 程序 - ![Java Program to add two complex numbers in Eclipse IDE](https://img.kancloud.cn/8a/4f/8a4f21bdefb6aa0a3a3c118968907243_1024x910.jpg) Eclipse IDE 中的输出: ![Output of adding two complex numbers in Java](https://img.kancloud.cn/a8/3a/a83a785b75fb5598ddf51c2789a5a6ce_836x162.jpg) 以下是一些相关的 java 示例: 1. 1. [Java 程序:找到最大的三个数字](https://beginnersbook.com/2017/09/java-program-to-find-largest-of-three-numbers/) 2. [Java 程序:使用`Switch Case`制作计算器](https://beginnersbook.com/2017/09/java-program-to-make-a-calculator-using-switch-case/) 3. [Java 程序:交换两个数字](https://beginnersbook.com/2017/09/java-program-to-swap-two-numbers-using-bitwise-xor-operator/) 4. [C++ 程序:相加两个复数](https://beginnersbook.com/2017/12/c-program-to-add-complex-numbers/)