ในส่วนนี้เราจะดูวิธีการสร้างและใช้งานจำนวนเชิงซ้อน (Complex Numbers) ในภาษา C++ เราสามารถสร้างคลาสสำหรับจำนวนเชิงซ้อนที่เก็บส่วนจริง (Real Part) และส่วนจินตภาพ (Imaginary Part) เป็นสมาชิกข้อมูล พร้อมกับฟังก์ชันสมาชิกต่างๆ เพื่อจัดการคลาสนี้
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
class Complex {
int real, img;
public:
Complex() {
// Default constructor: เริ่มต้นค่าที่ 0 + 0i
real = 0; img = 0;
}
Complex(int r, int i) {
// Parameterized constructor: เริ่มต้นค่าที่กำหนด
real = r; img = i;
}
void set();
void get();
void display();
friend Complex add(Complex, Complex);
friend Complex sub(Complex, Complex);
};
void Complex::set() {
cout << "Enter Real part: ";
cin >> real;
cout << "Enter Imaginary Part: ";
cin >> img;
}
void Complex::get() {
cout << "The complex number is: " << real << "+" << img << "i" << endl;
}
void Complex::display() {
if (img < 0) {
if (img == -1)
cout << "The complex number is: " << real << "-i" << endl;
else
cout << "The complex number is: " << real << img << "i" << endl;
} else {
if (img == 1)
cout << "The complex number is: " << real << " + i" << endl;
else
cout << "The complex number is: " << real << " + " << img << "i" << endl;
}
}
Complex add(Complex c1, Complex c2) {
Complex res;
res.real = c1.real + c2.real; // บวกส่วนจริง
res.img = c1.img + c2.img; // บวกส่วนจินตภาพ
return res;
}
Complex sub(Complex c1, Complex c2) {
Complex res;
res.real = c1.real - c2.real; // ลบส่วนจริง
res.img = c1.img - c2.img; // ลบส่วนจินตภาพ
return res;
}
int main() {
Complex n1(3, 2), n2(4, -3);
Complex result;
result = add(n1, n2);
result.display();
result = sub(n1, n2);
result.display();
return 0;
}
ผลลัพธ์
The complex number is: 7-i The complex number is: -1 + 5i
คำอธิบายเพิ่มเติม
ใน C++ มาตรฐาน (C++11 ขึ้นไป) มีไลบรารี <complex> สำหรับจำนวนเชิงซ้อนในตัวแล้ว ซึ่งรองรับชนิดข้อมูล float, double, และ long double พร้อมฟังก์ชันทางคณิตศาสตร์ครบถ้วน เช่น std::norm, std::arg, std::conj เป็นต้น การใช้ไลบรารีมาตรฐานจะช่วยลดความซับซ้อนและป้องกันข้อผิดพลาดได้ดีกว่าการสร้างคลาสเอง