示例: 将两个复数相加的源代码
// 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
在这个程序中,用户输入的两个复数存储在结构
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 一起打印将在输出中给我们两个负号。
因此,我们将值更改为正以避免符号重复。
在此之后,我们终于显示了总和。