在多项式c ++中找到x的值

时间:2017-10-16 19:37:45

标签: c++

#include <iostream>
#include <string>
#include <sstream>
#include <vector>

using namespace std;

int main()
{
    vector<double> coefficients;
    cout << "Enter the polynomial coefficients (increasing degree): ";
    string line;
    getline(cin,line);
    istringstream input_string(line);

    double coefficient;
    while (input_string >>coefficient)
    {
        coefficients.push_back(coefficient);
    }

    double x;
    cout <<"Enter the x value: ";
    cin >> x;

    double value = 0,power_x = 1;
    for (int i = 0; i < coefficients.size(); i++)
    value += coefficients[i] * power_x;
    power_x *= x;


    cout << "The value of the polynomial at x = " << x << " is " << value << endl;
    system ("pause");
}

嘿伙计们,写一个程序来计算一个程度越来越大的多项式的x的值,这是我的程序,我的教授要我输入以下内容作为输入:
系数为1 0 1 1.5表示x的值 但我的输出给了我2而不是3.25这是正确的答案。

1 个答案:

答案 0 :(得分:2)

power_x *= x;超出了你的for循环,因此只有当你希望每次迭代都执行它时才会执行一次。

你需要写下这个:

for (int i = 0; i < coefficients.size(); i++)
{
    value += coefficients[i] * power_x;
    power_x *= x;
}

然后在第一次迭代时,您获得value = 1*1power_x变为1.5,第二次迭代,值不变(递增0*1.5),power_x变为{ {1}},第三次迭代,值增加1.5*1.5

总计为1*1.5*1.5,等于1+1.5*1.5

使用调试器逐步调试代码可能比stackoverflow更快地发现它...

相关问题