多项式求值(迭代法)

#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;
}
发布了27 篇原创文章 · 获赞 1 · 访问量 1412

猜你喜欢

转载自blog.csdn.net/qq_34890856/article/details/104066132