C++ 通过将结构体传递给函数相加复数程序

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


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

// 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 num1, num2, complexSum;
    char signOfImag;

    cout << "For 1st complex number," << endl;
    cout << "Enter real and imaginary parts respectively:" << endl;
    cin >> num1.real >> num1.imag;

    cout << endl
         << "For 2nd complex number," << endl;
    cout << "Enter real and imaginary parts respectively:" << endl;
    cin >> num2.real >> num2.imag;

    // Call add function and store result in complexSum
    complexSum = addComplexNumbers(num1, num2);

    // Use Ternary Operator to check the sign of the imaginary number
    signOfImag = (complexSum.imag > 0) ? '+' : '-';

    // Use Ternary Operator to adjust the sign of the imaginary number
    complexSum.imag = (complexSum.imag > 0) ? complexSum.imag : -complexSum.imag;

    cout << "Sum = " << complexSum.real << signOfImag << complexSum.imag << "i";

    return 0;
}

complexNumber addComplexNumbers(complex num1, complex num2) {
    complex temp;
    temp.real = num1.real + num2.real;
    temp.imag = num1.imag + num2.imag;
    return (temp);
}

输出

For 1st complex number,
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

在此程序中,用户输入的两个复数存储在结构体 num1num2 中。

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

此结果存储在结构体 complexSum 中。

然后,计算和的虚部符号并存储在 char 变量 signOfImag 中。

// Use Ternary Operator to check the sign of the imaginary number
signOfImag = (complexSum.imag > 0) ? '+' : '-';

如果 complexSum 的虚部为正,则将 signOfImag 赋值为 '+'。否则,将其赋值为 '-'

然后我们调整 complexSum.imag 的值。

/// Use Ternary Operator to adjust the sign of the imaginary number
complexSum.imag = (complexSum.imag > 0) ? complexSum.imag : -complexSum.imag;

此代码将 complexSum.imag 更改为正值(如果发现其值为负)。

这是因为如果它是负数,那么与 signOfImag 一起打印将导致输出中有两个负号。

因此,我们将其值更改为正值以避免重复符号。

在此之后,我们最终显示和。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战