2017-10-16 39 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更快...