C++程序:通过传递结构体到函数来添加复数
复数是表示为 a+bi 的数,其中 i 是虚数单位,a 和 b 是实数。一些复数的例子如下:
2+5i 3-9i 8+2i
通过传递结构体到函数来添加复数的程序如下所示:
示例
#include <iostream> using namespace std; typedef struct complexNumber { float real; float imag; }; complexNumber addCN(complexNumber num1,complexNumber num2) { complexNumber temp; temp.real = num1.real + num2.real; temp.imag = num1.imag + num2.imag; return(temp); } int main() { complexNumber num1, num2, sum; cout << "Enter real part of Complex Number 1: " << endl; cin >> num1.real; cout << "Enter imaginary part of Complex Number 1: " << endl; cin >> num1.imag; cout << "Enter real part of Complex Number 2: " << endl; cin >> num2.real; cout << "Enter imaginary part of Complex Number 2: " << endl; cin >> num2.imag; sum = addCN(num1, num2); if(sum.imag >= 0) cout << "Sum of the two complex numbers is "<< sum.real <<" + "<< sum.imag <<"i"; else cout << "Sum of the two complex numbers is "<< sum.real <<" + ("<< sum.imag <<")i"; return 0; }
输出
以上程序的输出如下所示:
Enter real part of Complex Number 1: 5 Enter imaginary part of Complex Number 1: -9 Enter real part of Complex Number 2: 3 Enter imaginary part of Complex Number 2: 6 Sum of the two complex numbers is 8 + (-3)i
在以上程序中,结构体 complexNumber 包含复数的实部和虚部。如下所示:
struct complexNumber { float real; float imag; };
函数 addCN() 接收两个 complexNumber 类型的参数,并添加这两个数的实部和虚部。然后,将添加后的值返回到 main() 函数。如下所示:
complexNumber addCN(complexNumber num1,complexNumber num2) { complexNumber temp; temp.real = num1.real + num2.real; temp.imag = num1.imag + num2.imag; return(temp); }
在 main() 函数中,从用户获取数字的值。如下所示:
cout << "Enter real part of Complex Number 1: " << endl; cin >> num1.real; cout << "Enter imaginary part of Complex Number 1: " << endl; cin >> num1.imag; cout << "Enter real part of Complex Number 2: " << endl; cin >> num2.real; cout << "Enter imaginary part of Complex Number 2: " << endl; cin >> num2.imag;
通过调用 addCN() 函数获得两个数的和。然后打印该和。如下所示:
sum = addCN(num1, num2); if(sum.imag >= 0) cout << "Sum of the two complex numbers is "<< sum.real <<" + "<< sum.imag <<"i"; else cout << "Sum of the two complex numbers is "<< sum.real <<" + ("<< sum.imag <<")i";
广告