通过将结构体传递给函数来添加复数的 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
在这个程序中,用户输入的两个复数存储在结构体 num1
和 num2
中.
这两个结构体被传递给 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
将在输出中给我们两个负号。
因此,我们将值更改为正以避免符号重复。
在此之后,我们最终显示总和。