Добавил:
vvrstcnho
Рад, если кому-то помог
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:Лабораторные работы С++ (для ИВТ) / Готовые лабы С++ / Лаба1 / Laba 1 (12)
.cpp#include <iostream>
#include <vector>
#include <algorithm>
#include <windows.h>
using namespace std;
class Polynomial {
private:
vector<double> coefficients; // coefficients[i] - коэффициент при x^i
void normalize() {
while (!coefficients.empty() && coefficients.back() == 0) {
coefficients.pop_back();
}
if (coefficients.empty()) coefficients.push_back(0);
}
public:
Polynomial() {
coefficients.push_back(0);
cout << "Создан нулевой полином" << endl;
}
Polynomial(const vector<double>& coeffs) : coefficients(coeffs) {
normalize();
cout << "Создан полином из коэффициентов" << endl;
}
void input() {
cout << "Введите степень полинома: ";
int degree;
cin >> degree;
coefficients.resize(degree + 1);
cout << "Введите коэффициенты (от свободного члена до старшего):" << endl;
for (int i = 0; i <= degree; i++) {
cout << "Коэффициент при x^" << i << ": ";
cin >> coefficients[i];
}
normalize();
}
void output() {
cout << "Полином: ";
bool first = true;
for (int i = coefficients.size() - 1; i >= 0; i--) {
if (coefficients[i] != 0) {
if (!first && coefficients[i] > 0) cout << " + ";
if (coefficients[i] < 0) cout << " - ";
if (i == 0 || abs(coefficients[i]) != 1) {
if (!first) cout << abs(coefficients[i]);
else cout << coefficients[i];
}
if (i > 0) {
if (abs(coefficients[i]) != 1 || first) cout << abs(coefficients[i]);
cout << "x";
if (i > 1) cout << "^" << i;
}
first = false;
}
}
if (first) cout << "0";
cout << endl;
}
Polynomial add(const Polynomial& other) {
int maxSize = max(coefficients.size(), other.coefficients.size());
vector<double> result(maxSize, 0);
for (int i = 0; i < coefficients.size(); i++) result[i] += coefficients[i];
for (int i = 0; i < other.coefficients.size(); i++) result[i] += other.coefficients[i];
return Polynomial(result);
}
Polynomial multiply(const Polynomial& other) {
vector<double> result(coefficients.size() + other.coefficients.size() - 1, 0);
for (int i = 0; i < coefficients.size(); i++) {
for (int j = 0; j < other.coefficients.size(); j++) {
result[i + j] += coefficients[i] * other.coefficients[j];
}
}
return Polynomial(result);
}
};
int main() {
SetConsoleOutputCP(65001);
Polynomial p1, p2;
cout << "=== Работа с полиномами ===" << endl;
cout << "Введите первый полином:" << endl;
p1.input();
cout << "Введите второй полином:" << endl;
p2.input();
cout << "\nВведенные полиномы:" << endl;
cout << "Первый полином: "; p1.output();
cout << "Второй полином: "; p2.output();
Polynomial sum = p1.add(p2);
cout << "Сумма полиномов: "; sum.output();
Polynomial product = p1.multiply(p2);
cout << "Произведение полиномов: "; product.output();
return 0;
}
Соседние файлы в папке Лаба1
