如何在C++中使用类实现多项式方程?
在C++中用类实现多项式方程
下面是一个实用的多项式类实现方案,包含核心的构造、运算、求值和打印功能,完全满足作业需求:
类的核心设计
我们用vector<double>来存储多项式的系数,索引值对应项的次数——比如coefficients[0]是常数项,coefficients[1]是x¹的系数,coefficients[n]是xⁿ的系数。
完整代码实现
#include <iostream> #include <vector> #include <cmath> using namespace std; class Polynomial { private: vector<double> coefficients; // 移除末尾的零系数(优化打印效果) void trimTrailingZeros() { while (!coefficients.empty() && coefficients.back() == 0) { coefficients.pop_back(); } // 如果全零,保留一个0作为常数项 if (coefficients.empty()) { coefficients.push_back(0); } } public: // 默认构造函数(空多项式,等价于0) Polynomial() : coefficients{0} {} // 从系数列表构造多项式(比如{3,0,2}对应2x²+3) Polynomial(const vector<double>& coeffs) : coefficients(coeffs) { trimTrailingZeros(); } // 多项式求值:代入x计算结果 double evaluate(double x) const { double result = 0; for (int i = 0; i < coefficients.size(); ++i) { result += coefficients[i] * pow(x, i); } return result; } // 重载+运算符:多项式相加 Polynomial operator+(const Polynomial& other) const { vector<double> resultCoeffs; int maxDegree = max(coefficients.size(), other.coefficients.size()); resultCoeffs.resize(maxDegree, 0); for (int i = 0; i < coefficients.size(); ++i) { resultCoeffs[i] += coefficients[i]; } for (int i = 0; i < other.coefficients.size(); ++i) { resultCoeffs[i] += other.coefficients[i]; } return Polynomial(resultCoeffs); } // 重载-运算符:多项式相减 Polynomial operator-(const Polynomial& other) const { vector<double> resultCoeffs; int maxDegree = max(coefficients.size(), other.coefficients.size()); resultCoeffs.resize(maxDegree, 0); for (int i = 0; i < coefficients.size(); ++i) { resultCoeffs[i] += coefficients[i]; } for (int i = 0; i < other.coefficients.size(); ++i) { resultCoeffs[i] -= other.coefficients[i]; } return Polynomial(resultCoeffs); } // 打印多项式 void print() const { bool firstTerm = true; int degree = coefficients.size() - 1; for (int i = degree; i >= 0; --i) { double coeff = coefficients[i]; if (coeff == 0) continue; // 处理符号 if (!firstTerm) { cout << (coeff > 0 ? " + " : " - "); coeff = abs(coeff); } else { if (coeff < 0) { cout << "-"; coeff = abs(coeff); } firstTerm = false; } // 处理系数和次数 if (i == 0) { cout << coeff; } else if (i == 1) { if (coeff != 1) cout << coeff; cout << "x"; } else { if (coeff != 1) cout << coeff; cout << "x^" << i; } } cout << endl; } }; // 示例用法 int main() { // 创建多项式:2x² + 0x + 3(即2x²+3) Polynomial p1({3, 0, 2}); // 创建多项式:-x + 5(即5 - x) Polynomial p2({5, -1}); cout << "多项式p1: "; p1.print(); cout << "多项式p2: "; p2.print(); Polynomial sum = p1 + p2; cout << "p1 + p2: "; sum.print(); double x = 2; cout << "p1在x=" << x << "处的值: " << p1.evaluate(x) << endl; return 0; }
关键功能说明
- 构造函数:支持默认构造(零多项式)和从系数列表构造,自动移除末尾零系数优化显示。
- 求值函数:代入任意x值计算多项式结果,用
pow()处理幂次。 - 运算符重载:实现了多项式的加减运算,方便直接用
+、-操作。 - 打印函数:智能处理符号、系数为1/0的情况,输出符合数学习惯的格式。
扩展建议(可选)
如果作业要求更高,可以添加这些功能:
- 重载
*运算符实现多项式乘法 - 添加求导、积分函数
- 支持浮点数系数的精确比较(避免因精度问题误判零系数)
内容的提问来源于stack exchange,提问作者Ammar shah
相关产品推荐
相关产品推荐

