Напиши библиотеку на C++, осуществляющую работу с комплексными числами. Необходимо…
- User
Напиши библиотеку на C++, осуществляющую работу с комплексными числами. Необходимо реализовать операции сложения, вычитания, умножения.
- Assistant
Вот пример реализации библиотеки для работы с комплексными числами на C++:
#include <iostream> class Complex { private: double real; double imag; public: Complex(double real = 0.0, double imag = 0.0) : real(real), imag(imag) {} double getReal() const { return real; } double getImag() const { return imag; } Complex operator+(const Complex& other) const { return Complex(real + other.real, imag + other.imag); } Complex operator-(const Complex& other) const { return Complex(real - other.real, imag - other.imag); } Complex operator*(const Complex& other) const { double newReal = real * other.real - imag * other.imag; double newImag = real * other.imag + imag * other.real; return Complex(newReal, newImag); } friend std::ostream& operator<<(std::ostream& os, const Complex& complex) { os << complex.real; if (complex.imag >= 0.0) os << '+'; os << complex.imag << 'i'; return os; } }; int main() { Complex c1(2.5, 3.8); Complex c2(1.3, -4.6); Complex sum = c1 + c2; Complex difference = c1 - c2; Complex product = c1 * c2; std::cout << "Sum: " << sum << std::endl; std::cout << "Difference: " << difference << std::endl; std::cout << "Product: " << product << std::endl; return 0; }