复数是表示为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";