2017-10-16 55 views
-1
#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这是正确的答案。求x的值多项式C++

回答

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.5*1.5,第三次迭代,值增加1*1.5*1.5

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

使用调试器一步一步地调试您的代码可能会发现这比stackoverflow更快...