Polynomial类C++
时间: 2023-11-14 16:25:06 浏览: 82
Polynomial类是一个常见的数学类,用于存储和操作多项式。以下是一个简单的Polynomial类的C++代码示例:
```c++
#include <iostream>
#include <vector>
using namespace std;
class Polynomial {
private:
vector<double> coefficients;
public:
Polynomial() {}
Polynomial(vector<double> coeffs) {
coefficients = coeffs;
}
int degree() {
return coefficients.size() - 1;
}
double operator[](int i) const {
return coefficients[i];
}
double& operator[](int i) {
return coefficients[i];
}
Polynomial operator+(const Polynomial& other) const {
vector<double> result(max(degree(), other.degree()) + 1);
for (int i = 0; i <= degree(); i++) {
result[i] += coefficients[i];
}
for (int i = 0; i <= other.degree(); i++) {
result[i] += other.coefficients[i];
}
return Polynomial(result);
}
Polynomial operator-(const Polynomial& other) const {
vector<double> result(max(degree(), other.degree()) + 1);
for (int i = 0; i <= degree(); i++) {
result[i] += coefficients[i];
}
for (int i = 0; i <= other.degree(); i++) {
result[i] -= other.coefficients[i];
}
return Polynomial(result);
}
Polynomial operator*(const Polynomial& other) const {
vector<double> result(degree() + other.degree() + 1);
for (int i = 0; i <= degree(); i++) {
for (int j = 0; j <= other.degree(); j++) {
result[i + j] += coefficients[i] * other.coefficients[j];
}
}
return Polynomial(result);
}
friend ostream& operator<<(ostream& os, const Polynomial& p) {
for (int i = p.degree(); i >= 0; i--) {
if (p[i] == 0) {
continue;
}
if (i == p.degree()) {
os << p[i] << "x^" << i;
} else if (i == 1) {
os << " + " << p[i] << "x";
} else {
os << " + " << p[i] << "x^" << i;
}
}
return os;
}
};
int main() {
vector<double> coeffs1 = {1, 2, 3};
vector<double> coeffs2 = {4, 5, 6};
Polynomial p1(coeffs1);
Polynomial p2(coeffs2);
cout << "p1 = " << p1 << endl;
cout << "p2 = " << p2 << endl;
Polynomial p3 = p1 + p2;
Polynomial p4 = p1 - p2;
Polynomial p5 = p1 * p2;
cout << "p1 + p2 = " << p3 << endl;
cout << "p1 - p2 = " << p4 << endl;
cout << "p1 * p2 = " << p5 << endl;
return 0;
}
```
这个Polynomial类支持多项式的加、减和乘法,并且可以输出多项式的字符串表示。
阅读全文