2017-10-16 14 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の値を計算するプログラムを書くことは、ここに私のプログラムだと私の教授は、入力として、以下を入力するように私を望んでxの値を見つけます1 0 1の係数は 1.5のx の値ですが、私の出力は正しい答えである3.25の代わりに2を返します。多項式C++

答えて

2

power_x *= x;はforループの対象外です。したがって、すべての反復で実行されると予想される場合にのみ1回実行されます。

あなたはこの記述する必要があります。値は、あなたがvalue = 1*1power_x1.5なりを得る最初の反復に続いて

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

を、第2の繰り返し、値は変更されません(0*1.5ずつ増加)、power_x1.5*1.5なり、3回目の反復インクリメント:1*1.5*1.5

合計は1+1.5*1.5であり、3.25に等しい。

デバッガを使用してコードを段階的にデバッグすると、おそらくスタックオーバーフローよりも速くこのコードが検出されます。