Số phức là số biểu diễn dạng a+bi với i là số ảo, a, b là số thực. Ví dụ:
2+5i 3-9i 8+2i
Chương trình cộng số phức bằng cách truyền struct vào hàm:
Ví dụ
#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; }Kết quả
Kết quả chương trình:
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
Trong chương trình, struct complexNumber chứa phần thực và ảo:
struct complexNumber { float real; float imag; };Hàm addCN() nhận hai tham số kiểu complexNumber, cộng phần thực và ảo, trả về kết quả cho main():
complexNumber addCN(complexNumber num1,complexNumber num2) { complexNumber temp; temp.real = num1.real + num2.real; temp.imag = num1.imag + num2.imag; return(temp); }Trong main(), giá trị số lấy từ người dùng:
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;
Tổng hai số bằng cách gọi addCN(). Sau đó in tổng:
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";