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


2023年1月21日, Learn eTutorial
1571

在这个 C++ 程序中,我们将两个复数作为结构体,并通过函数将它们相加。

什么是复数?

复数是一种数系中的元素,包含实数和一个特定元素 'i',称为虚数单位,满足方程 i2 = -1。此外,每个复数都可以表示为 a + bi 的形式,其中 a b 是实数。

如何添加两个复数?

要添加或减去两个复数,我们需要将数的实部和虚部相加。例如,2 + 1i3 + 2i 的和是 5 + 3i。

如何在 C++ 中将结构体传递给函数?

结构体变量可以像普通参数一样传递给函数。

如何创建一个 C++ 程序,通过将结构体传递给函数来添加复数?

这里我们创建一个名为 complex 的结构体,并将其数据成员命名为 realimag。在这个 C++ 程序中,用户输入的两个复数存储在结构体 num1num2 中。

现在我们需要将这两个结构体传递给函数,它将进行计算并返回结果。然后,我们计算结果的虚部符号并将其存储在一个变量中。

算法

步骤1:  调用头文件iostream。

第 2 步:使用 namespace std

第 3 步:  创建一个名为 complex 的结构体,并将 real, imag 作为其数据成员。

第 4 步:将用户输入的两个复数存储在结构体 num1num2 中。

第 5 步: 创建一个函数 addcomplexNumbers() ,它计算和并将结果返回给 main() 函数。

第 6 步:将结构体 num1 num2 传递给函数 addComplexNumbers()

第 7 步: 将结果存储在结构体 complexSum 中。

第 8 步: 确定和的虚部符号,并将其存储在 char 变量 signOfImag 中。

第 9 步: 如果 complexSum 的虚部值为正,则将 signOfImag 的值赋为 +。如果为负,则赋为 –。

第 10 步: 显示结果。

第 11 步: 退出。
 

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:
2.5
3.5
For 2nd complex number,
Enter real and imaginary parts respectively:
4.2
-2.1
Sum = 6.7+1.4i