企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# C++ 程序:通过将结构传递给函数来相加复数 > 原文: [https://www.programiz.com/cpp-programming/examples/complex-number-add](https://www.programiz.com/cpp-programming/examples/complex-number-add) #### 该程序将两个复数作为结构并通过使用函数将它们相加。 要理解此示例,您应该了解以下 [C++ 编程](/cpp-programming "C++ tutorial")主题: * [C++ 结构](/cpp-programming/structure) * [C++ 结构和函数](/cpp-programming/structure-function) * * * * * * ## 示例:相加两个复数的源代码 ```cpp // Complex numbers are entered by the user #include <iostream> using namespace std; typedef struct complex { float real; float imag; } complexNumber; complexNumber addComplexNumbers(complex, complex); int main() { complexNumber n1, n2, temporaryNumber; char signOfImag; cout << "For 1st complex number," << endl; cout << "Enter real and imaginary parts respectively:" << endl; cin >> n1.real >> n1.imag; cout << endl << "For 2nd complex number," << endl; cout << "Enter real and imaginary parts respectively:" << endl; cin >> n2.real >> n2.imag; signOfImag = (temporaryNumber.imag > 0) ? '+' : '-'; temporaryNumber.imag = (temporaryNumber.imag > 0) ? temporaryNumber.imag : -temporaryNumber.imag; temporaryNumber = addComplexNumbers(n1, n2); cout << "Sum = " << temporaryNumber.real << temporaryNumber.imag << "i"; return 0; } complexNumber addComplexNumbers(complex n1,complex n2) { complex temp; temp.real = n1.real+n2.real; temp.imag = n1.imag+n2.imag; return(temp); } ``` **输出** ```cpp Enter real and imaginary parts respectively: 3.4 5.5 For 2nd complex number, Enter real and imaginary parts respectively: -4.5 -9.5 Sum = -1.1-4i ``` 在问题中,用户输入的两个复数存储在结构`n1`和`n2`中。 这两个结构传递给`addComplexNumbers()`函数,该函数计算总和并将结果返回给`main()`函数。 最后,通过`main()`函数显示总和。