Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Số phức (Complex Numbers) trong C++

C++ cho phép tự xây dựng lớp số phức hoặc sử dụng thư viện chuẩn <complex>. Bài này demo tự cài đặt lớp complex với các phép toán cơ bản.

Lớp số phức tự định nghĩa

#include <iostream>
using namespace std;

class complex {
    int real, img;
public:
    complex() : real(0), img(0) {}
    complex(int r, int i) : real(r), img(i) {}

    void set() {
        cout << "Enter Real part: "; cin >> real;
        cout << "Enter Imaginary Part: "; cin >> img;
    }
    void get() { cout << "The complex number is: " << real << "+" << img << "i" << endl; }
    void 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;
        }
    }
    friend complex add(complex, complex);
    friend complex sub(complex, complex);
};

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), result;
    result = add(n1, n2); result.display(); // 7 - i
    result = sub(n1, n2); result.display(); // -1 + 5i
    return 0;
}

Kết quả

The complex number is: 7-i
The complex number is: -1 + 5i

Sử dụng thư viện chuẩn <complex> (Khuyên dùng)

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

int main() {
    complex<double> z1(3.0, 2.0), z2(4.0, -3.0);
    cout << "z1 = " << z1 << endl;        // (3,2)
    cout << "z2 = " << z2 << endl;        // (4,-3)
    cout << "z1 + z2 = " << z1 + z2 << endl; // (7,-1)
    cout << "z1 - z2 = " << z1 - z2 << endl; // (-1,5)
    cout << "z1 * z2 = " << z1 * z2 << endl; // (18,-1)
    cout << "abs(z1) = " << abs(z1) << endl;  // 3.60555
    cout << "arg(z1) = " << arg(z1) << endl;  // 0.588003 rad
    return 0;
}

Ưu điểm của std::complex

  • Template hỗ trợ float, double, long double.
  • Hỗ trợ đầy đủ: +, -, *, /, so sánh, hàm lượng giác, mũ, log, căn, cực đại/cực tiểu...
  • Tối ưu hóa, chuẩn hóa, tránh lỗi tự viết (ví dụ: xử lý dấu phần ảo, chia cho 0).
  • Tương thích STL algorithms.

Khi nào tự viết?

  • Bài tập học tập, hiểu bản chất.
  • Yêu cầu đặc biệt: kiểu dữ liệu tùy chỉnh, điểm cố định (fixed-point), số phức modulo...