จำนวนเชิงซ้อนคือตัวเลขที่แสดงเป็น 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
ในโปรแกรมด้านบน โครงสร้างจำนวนเชิงซ้อนประกอบด้วยส่วนจริงและส่วนจินตภาพของจำนวนเชิงซ้อน ด้านล่างนี้ −
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";