一元多项式的加法和减法c++
时间: 2024-10-18 12:16:39 浏览: 33
在C++中,一元多项式通常表示为一个数列,其中每个元素是一个系数乘以变量的幂次。例如,\(a_nx^n + a_{n-1}x^{n-1} + ... + a_1x + a_0\)。对于一元多项式的加法和减法,你可以创建一个类来存储这些数据,并提供相应的操作方法。
首先,我们可以定义一个`Polynomial`类,包含一个向量`(std::vector<double>)`来存储系数和一个整型变量`degree`表示最高幂次:
```cpp
class Polynomial {
private:
std::vector<double> coefficients;
int degree;
public:
// 构造函数,添加常数项
Polynomial(double c = 0) : coefficients({c}), degree(0) {}
// 添加项到多项式
void addTerm(double coef, int power) {
if (coef != 0 && power > degree) {
coefficients.resize(power+1);
coefficients[degree] = 0;
degree = power;
}
coefficients[degree] += coef;
}
// 用于加法和减法的运算
friend Polynomial operator+(const Polynomial& p1, const Polynomial& p2);
friend Polynomial operator-(const Polynomial& p1, const Polynomial& p2);
};
```
然后,实现加法和减法的运算符重载:
```cpp
Polynomial operator+(const Polynomial& p1, const Polynomial& p2) {
Polynomial result(p1.degree >= p2.degree ? p1 : p2); // 将较大多项式复制给结果
for (int i = 0; i <= result.degree; ++i) {
result.coefficients[i] += p1.coefficients[i] + p2.coefficients[i];
}
return result;
}
Polynomial operator-(const Polynomial& p1, const Polynomial& p2) {
Polynomial result(p1.degree >= p2.degree ? p1 : p2);
for (int i = 0; i <= result.degree; ++i) {
result.coefficients[i] -= p2.coefficients[i];
}
return result;
}
```
现在你就可以创建`Polynomial`对象并进行加法和减法了:
```cpp
Polynomial p1(2, 1, -1), p2(4, 3, 5);
Polynomial sum = p1 + p2; // sum 现在是 6x^2 + 4x + 4 - 1x
Polynomial diff = p1 - p2; // diff 现在是 -2x^2 - 4x - 7
```
阅读全文