复数的四则运算公式:
1.复数的加法运算
(a+bi)+(c+di)=(a+c)+(b+d)i
2.复数的减法运算
(a+bi)+(c+di)=(a-c)+(b-d)i
3.复数的乘法运算
(a+bi)(c+di)=(ac-bd)+(bc+ad)i
4.复数的除法运算
(a+bi)/(c+di)
=(ac + bd)/(c^2 + d ^2) +((bc - ad)/(c ^2 + d ^2)) i
#includeusing namespace std; class Complex { private: double real; double image; public: Complex(const Complex& complex) :real{ complex.real }, image{ complex.image } { } Complex(double Real = 0, double Image = 0) :real{ Real }, image{ Image } { } //TODO friend istream& operator >> (istream& in, Complex& z) { in >> z.real >> z.image; return in; } friend ostream& operator << (ostream& out, const Complex& z) { out << "("; if (z.real >= 1e-7 || (z.real < 1e-7 && z.real > -1e-7)) out.unsetf(std::ios::showpos); out << z.real; out.setf(std::ios::showpos); out << z.image; out << "i)"; return out; } friend Complex operator+(const Complex& A, const Complex& B) { Complex C; C.real = A.real + B.real; C.image = A.image + B.image; return C; } friend Complex operator-(const Complex& A, const Complex& B) { Complex C; C.real = A.real - B.real; C.image = A.image - B.image; return C; } friend Complex operator*(const Complex& A, const Complex& B) { Complex C; C.real = A.real * B.real - A.image * B.image; C.image = A.real * B.image + A.image * B.real; return C; } friend Complex operator/(const Complex& A, const Complex& B) { Complex C; C.real = (A.real * B.real + A.image * B.image) / (B.real * B.real + B.image * B.image); C.image = (A.image * B.real - A.real * B.image) / (B.real * B.real + B.image * B.image); return C; } Complex operator+(const Complex c) { return Complex(this->real + c.real, this->image + c.image); } Complex operator-(const Complex c) { return Complex(this->real - c.real, this->image - c.image); } Complex operator*(const Complex c) { return Complex(this->real * c.real - this->image * c.image, this->real * c.image + this->image * c.real); } Complex operator/(const Complex c) { return Complex((this->real * c.real + this->image * c.image) / (c.real * c.real + c.image * c.image), (this->image * c.real - this->real * c.image) / (c.real * c.real + c.image * c.image)); } }; int main() { Complex z1, z2; cin >> z1; cin >> z2; cout << z1 << " " << z2 << endl; cout << z1 + z2 << endl; cout << z1 - z2 << endl; cout << z1 * z2 << endl; cout << z1 / z2 << endl; return 0; }
参考链接:https://blog.csdn.net/weixin_42004975/article/details/111589053



