原文: https://www.programiz.com/cpp-programming/examples/complex-number-add

该程序将两个复数作为结构并通过使用函数将它们相加。

要理解此示例,您应该了解以下 C++ 编程主题:



示例:相加两个复数的源代码

  1. // Complex numbers are entered by the user
  2. #include <iostream>
  3. using namespace std;
  4. typedef struct complex
  5. {
  6. float real;
  7. float imag;
  8. } complexNumber;
  9. complexNumber addComplexNumbers(complex, complex);
  10. int main()
  11. {
  12. complexNumber n1, n2, temporaryNumber;
  13. char signOfImag;
  14. cout << "For 1st complex number," << endl;
  15. cout << "Enter real and imaginary parts respectively:" << endl;
  16. cin >> n1.real >> n1.imag;
  17. cout << endl << "For 2nd complex number," << endl;
  18. cout << "Enter real and imaginary parts respectively:" << endl;
  19. cin >> n2.real >> n2.imag;
  20. signOfImag = (temporaryNumber.imag > 0) ? '+' : '-';
  21. temporaryNumber.imag = (temporaryNumber.imag > 0) ? temporaryNumber.imag : -temporaryNumber.imag;
  22. temporaryNumber = addComplexNumbers(n1, n2);
  23. cout << "Sum = " << temporaryNumber.real << temporaryNumber.imag << "i";
  24. return 0;
  25. }
  26. complexNumber addComplexNumbers(complex n1,complex n2)
  27. {
  28. complex temp;
  29. temp.real = n1.real+n2.real;
  30. temp.imag = n1.imag+n2.imag;
  31. return(temp);
  32. }

输出

  1. Enter real and imaginary parts respectively:
  2. 3.4
  3. 5.5
  4. For 2nd complex number,
  5. Enter real and imaginary parts respectively:
  6. -4.5
  7. -9.5
  8. Sum = -1.1-4i

在问题中,用户输入的两个复数存储在结构n1n2中。

这两个结构传递给addComplexNumbers()函数,该函数计算总和并将结果返回给main()函数。

最后,通过main()函数显示总和。