polynomial类c++
时间: 2023-12-03 11:53:31 浏览: 121
以下是一个简单的C++ Polynomial类的示例。
```c++
#include <iostream>
#include <vector>
using namespace std;
class Polynomial {
private:
vector<int> coeffs;
public:
Polynomial() {}
Polynomial(const vector<int>& c) {
coeffs = c;
}
int degree() const {
return coeffs.size() - 1;
}
int operator[](int i) const {
if (i >= coeffs.size()) {
return 0;
}
return coeffs[i];
}
int& operator[](int i) {
if (i >= coeffs.size()) {
coeffs.resize(i+1);
}
return coeffs[i];
}
Polynomial operator+(const Polynomial& other) const {
vector<int> res(max(coeffs.size(), other.coeffs.size()));
for (int i = 0; i < res.size(); i++) {
res[i] = (*this)[i] + other[i];
}
return Polynomial(res);
}
Polynomial operator-(const Polynomial& other) const {
vector<int> res(max(coeffs.size(), other.coeffs.size()));
for (int i = 0; i < res.size(); i++) {
res[i] = (*this)[i] - other[i];
}
return Polynomial(res);
}
Polynomial operator*(const Polynomial& other) const {
vector<int> res(coeffs.size() + other.coeffs.size() - 1);
for (int i = 0; i < coeffs.size(); i++) {
for (int j = 0; j < other.coeffs.size(); j++) {
res[i+j] += (*this)[i] * other[j];
}
}
return Polynomial(res);
}
void print() const {
for (int i = coeffs.size()-1; i >= 0; i--) {
if (coeffs[i] != 0) {
if (i == coeffs.size()-1) {
cout << coeffs[i] << "x^" << i;
} else {
cout << " + " << coeffs[i] << "x^" << i;
}
}
}
cout << endl;
}
};
int main() {
vector<int> c1 = {1, 2, 3};
vector<int> c2 = {4, 5};
Polynomial p1(c1);
Polynomial p2(c2);
Polynomial p3 = p1 + p2;
Polynomial p4 = p1 * p2;
p1.print();
p2.print();
p3.print();
p4.print();
return 0;
}
```
上述代码实现了一个简单的Polynomial类,支持多项式加减乘,以及输出多项式的功能。
阅读全文