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

โปรแกรม C++ บวก Complex Numbers ด้วย Structure

Complex Number: a + bi โดย a = Real Part, b = Imaginary Part, i = √(-1)

โครงสร้าง Struct

struct Complex {
    float real;
    float imag;
};

ฟังก์ชันบวก Complex

Complex addComplex(Complex n1, Complex n2) {
    Complex temp;
    temp.real = n1.real + n2.real;
    temp.imag = n1.imag + n2.imag;
    return temp;
}

โปรแกรมสมบูรณ์

#include <iostream>
using namespace std;

struct Complex {
    float real;
    float imag;
};

Complex addComplex(Complex n1, Complex n2) {
    Complex temp;
    temp.real = n1.real + n2.real;
    temp.imag = n1.imag + n2.imag;
    return temp;
}

int main() {
    Complex n1, n2, sum;
    
    cout << "Complex 1 - Real: ";  cin >> n1.real;
    cout << "Complex 1 - Imag: ";  cin >> n1.imag;
    cout << "Complex 2 - Real: ";  cin >> n2.real;
    cout << "Complex 2 - Imag: ";  cin >> n2.imag;
    
    sum = addComplex(n1, n2);
    
    if (sum.imag >= 0)
        cout << "Sum = " << sum.real << " + " << sum.imag << "i";
    else
        cout << "Sum = " << sum.real << " " << sum.imag << "i";
    return 0;
}

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

Complex 1 - Real: 5
Complex 1 - Imag: -9
Complex 2 - Real: 3
Complex 2 - Imag: 6
Sum = 8 + -3i

C++ STL: std::complex

#include <complex>
#include <iostream>

int main() {
    std::complex<double> c1(5, -9);
    std::complex<double> c2(3, 6);
    std::complex<double> sum = c1 + c2;  // Operator+ Overloaded
    std::cout << "Sum = " << sum;        // (8,-3)
    return 0;
}

ใช้ std::complex<T> จาก <complex> ใน Production Code (มี +, -, *, /, abs, arg, norm, polar, ฯลฯ)