复数的四则运算

题目描述

请先完成《神奇的字面量运算符》题目。

定义类 Complex 及必要的函数,使得程序符合下文规定的输入输出。

关于输入

两行,具有形式 x+yi,其中 x 和 y 是 double 范围内的浮点数。(即使虚部是非正数,也带+符号。)

记这两个形式所指明的复数为 a 和 b。

关于输出

若干行复数,每行以 x+yi 形式输出(即使虚部是非正数,也输出+符号)。

第一行:3+-5i

第二行:a+b

第三行:a-b

第四行:a*b

第五行:a/b

第六行:42-a

第七行:3.14-a

第八行:42/a

第九行:3.14/a

第十行:42*a

第十一行:3.14*a

第十二行:a*i

参考答案

#include <cmath>
#include <iostream>
struct Complex {
    double real;
    double imag;

    Complex(double real = 0, double imag = 0) : real{real}, imag{imag} {}

    Complex inverse() const {
        auto num = real * real + imag * imag;
        return {real / num, -imag / num};
    }

    friend double abs(const Complex& c) {
        return std::sqrt(c.real * c.real + c.imag * c.imag);
    }
};

Complex operator""_i(unsigned long long s) {
    return {0, double(s)};
}

Complex operator""_i(long double s) {
    return {0, double(s)};
}

std::ostream& operator<<(std::ostream& os, const Complex& c) {
    return os << c.real << "+" << c.imag << 'i';
}
std::istream& operator>>(std::istream& is, Complex& c) {
    char ignore;
    return is >> c.real >> ignore >> c.imag >> ignore;
}

Complex operator+(const Complex& a, const Complex& b) {
    return {a.real + b.real, a.imag + b.imag};
}
Complex operator-(const Complex& a, const Complex& b) {
    return {a.real - b.real, a.imag - b.imag};
}
Complex operator*(const Complex& a, const Complex& b) {
    return {a.real * b.real - a.imag * b.imag, a.real * b.imag + a.imag * b.real};
}
Complex operator/(const Complex& a, const Complex& b) {
    return a * b.inverse();
}
int main() {
    std::cout << 3.0 - 5_i << std::endl;

    Complex a, b = 0;
    int n = 42;
    double x = 3.14;

    std::cin >> a >> b;
    std::cout << a + b << std::endl;
    std::cout << a - b << std::endl;
    std::cout << a * b << std::endl;
    std::cout << a / b << std::endl;

    std::cout << n - a << std::endl;
    std::cout << x - a << std::endl;
    std::cout << n / a << std::endl;
    std::cout << x / a << std::endl;
    std::cout << n * a << std::endl;
    std::cout << x * a << std::endl;


    using std::abs;
    auto r = 1 + 1_i;
    auto deg45 = r / abs(r);
    std::cout << a * deg45 * deg45 << std::endl;
}