C++教程
C++控制语句
C++函数
C++数组
C++指针
C++对象
C++继承
C++多态
C++抽象
C++常用
C++ STL教程
C++迭代器
C++程序

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

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

该程序以两个复数为结构,使用函数相加。
要理解此示例,您应该了解以下C++ 编程 主题:
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);
}
输出
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 一起打印将在输出中给我们两个负号。
因此,我们将值更改为正以避免符号重复。
在此之后,我们终于显示了总和。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4