跳转至

复数

模版
C++
template<class T = double>
struct __Complex {
    T x, y;
    __Complex() = default;
    __Complex(const T x, const T y) : x(x), y(y) {}
    __Complex& operator+=(const __Complex &b) {
        x += b.x;
        y += b.y;
        return *this;
    }
    __Complex& operator-=(const __Complex &b) {
        x -= b.x;
        y -= b.y;
        return *this;
    }
    __Complex& operator*=(const __Complex &b) {
        __Complex temp;
        temp.x = x * b.x - y * b.y;
        temp.y = x * b.y + y * b.x;
        *this = temp;
        return *this;
    }
    __Complex& operator*=(const T &b) {
        x *= b;
        y *= b;
        return *this;
    }
    __Complex& operator/=(const __Complex &b) {
        __Complex temp;
        temp.x = (x * b.x + y * b.y) / (b.x * b.x + b.y * b.y);
        temp.y = (y * b.x - x * b.y) / (b.x * b.x + b.y * b.y);
        *this = temp;
        return *this;
    }
    __Complex& operator/=(const T b) {
        x /= b;
        y /= b;
        return *this;
    }
    __Complex operator+(const __Complex &b) {
        __Complex a = *this;
        a += b;
        return a;
    }
    __Complex operator-(const __Complex &b) {
        __Complex a = *this;
        a -= b;
        return a;
    }
    __Complex operator*(const __Complex &b) {
        __Complex a = *this;
        a *= b;
        return a;
    }
    __Complex operator/(const __Complex &b) {
        __Complex a = *this;
        a /= b;
        return a;
    }
    friend istream& operator>>(istream &is, __Complex &a) {
        is >> a.x >> " " >> a.y;
        return is;
    }
    friend ostream& operator<<(ostream &os, const __Complex &a) {
        os << fixed << setprecision(5) << a.x << " " << a.y;
        return os;
    }
}; // __Complex
using Complex = __Complex<>;
// 复数类
// 实现了 复数之间的加减乘除运算
// 实现了 复数的输入输出
// 实现了 复数与整形/浮点型变量之间的乘除运算
// 类型名称 Complex