多项式求值(迭代法)
程序员文章站
2022-03-15 19:32:07
...
#include <vector>
#include <iostream>
#include <string>
using namespace std;
class Polynomial
{
private:
const int MAXTERMS = 99;
vector<double> m_CoefficientVector;//下标即指数
public:
Polynomial() {}
~Polynomial() {}
void inputCoefficientAndExponent()
{
double coefficient;
int exponent;
for (int i = 0; i <MAXTERMS; i++) {
m_CoefficientVector.push_back(0);
}
printf_s("input coef exp (when exp = -1 stop input.) :\n");
while (true) {
scanf_s("%lf %d", &coefficient, &exponent);
if (exponent == -1) break;
m_CoefficientVector[exponent] = coefficient;
}
}
void PolynomialValue(double x)
{
int endCoef = MAXTERMS-1;
double tmpResult = m_CoefficientVector.at(endCoef);
while (endCoef != 0)
{
tmpResult = tmpResult * x +
m_CoefficientVector.at(--endCoef);
}
printf_s("Polynomial(%3.2lf) = %3.2lf\n", x, tmpResult);
}
};
int main()
{
Polynomial pol;
pol.inputCoefficientAndExponent();
pol.PolynomialValue(2.0);
system("pause");
return 0;
}