Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ คูณจำนวนเชิงซ้อน (Complex Number Multiplication)

จำนวนเชิงซ้อน (Complex Number) มีรูปแบบ a + bi โดยที่:

  • a = ส่วนจริง (Real part)
  • b = ส่วนจินตภาพ (Imaginary part)
  • i = หน่วยจินตภาพ โดยที่ i² = -1

ตัวอย่างจำนวนเชิงซ้อน

2 + 3i
5 + 9i
4 + 2i

สูตรการคูณ

(a + bi) × (c + di) = (ac - bd) + (ad + bc)i

โค้ดโปรแกรม

#include <iostream>
using namespace std;

int main() {
    int x1, y1, x2, y2, x3, y3;
    
    cout << "Enter the first complex number (real imag): ";
    cin >> x1 >> y1;
    
    cout << "Enter the second complex number (real imag): ";
    cin >> x2 >> y2;
    
    // สูตร: (x1 + y1i)(x2 + y2i) = (x1*x2 - y1*y2) + (x1*y2 + y1*x2)i
    x3 = x1 * x2 - y1 * y2;  // ส่วนจริง
    y3 = x1 * y2 + y1 * x2;  // ส่วนจินตภาพ
    
    cout << "The value after multiplication is: " << x3 << " + " << y3 << " i";
    return 0;
}

ผลลัพธ์ตัวอย่าง

Enter the first complex number: 2 1
Enter the second complex number: 3 4
The value after multiplication is: 2 + 11 i

การตรวจสอบคำนวณ

(2 + 1i) × (3 + 4i)
= (2×3 - 1×4) + (2×4 + 1×3)i
= (6 - 4) + (8 + 3)i
= 2 + 11i  ✓

ขยายความสามารถ

สามารถปรับปรุงได้โดย:

  • ใช้ struct หรือ class สำหรับ Complex Number
  • เพิ่ม operator overloading สำหรับ +, -, *, /
  • ใช้ <complex> header ของ C++ STL (std::complex<double>)
  • รองรับ float/double แทน int เพื่อความแม่นยำ

ตัวอย่างใช้ std::complex

#include <iostream>
#include <complex>
using namespace std;

int main() {
    complex<double> c1(2, 1), c2(3, 4);
    complex<double> result = c1 * c2;
    cout << "Result: " << result;  // แสดงเป็น (2,11)
    return 0;
}