Напиши код на c++: Разработать класс, описывающий комплексное число class Complex {…
- User
Напиши код на c++: Разработать класс, описывающий комплексное число class Complex { float real; float imag; }; Для данного класса разработать следующие методы: • конструктор; • get-методы, возвращающие действительную и мнимую части; • перегрузить методы сложения, вычитания, деления и умножения комплексных чисел; • перегрузить метод вывода комплексного числа на экран
- Assistant
Вот пример реализации класса
Complex, описывающего комплексное число и его методы на C++:#include <iostream> class Complex { private: float real; float imag; public: // Конструктор Complex(float r = 0.0f, float i = 0.0f) : real(r), imag(i) {} // Get-методы float getReal() const { return real; } float 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 { return Complex(real * other.real - imag * other.imag, real * other.imag + imag * other.real); } // Деление комплексных чисел Complex operator/(const Complex& other) const { float denominator = other.real * other.real + other.imag * other.imag; return Complex((real * other.real + imag * other.imag) / denominator, (imag * other.real - real * other.imag) / denominator); } // Перегрузка оператора вывода для комплексных чисел friend std::ostream& operator<<(std::ostream& os, const Complex& c) { if (c.imag < 0) { os << c.real << " - " << -c.imag << "i"; } else { os << c.real << " + " << c.imag << "i"; } return os; } }; int main() { Complex c1(3.0, 2.0); Complex c2(1.0, -4.0); std::cout << "C1: " << c1 << std::endl; std::cout << "C2: " << c2 << std::endl; std::cout << "C1 + C2: " << c1 + c2 << std::endl; std::cout << "C1 - C2: " << c1 - c2 << std::endl; std::cout << "C1 * C2: " << c1 * c2 << std::endl; std::cout << "C1 / C2: " << c1 / c2 << std::endl; return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.