2015-05-14 203 views
0

,所以這是我的代碼片段:while循環繼續運行

double numericalMethod::splineLinearInterpolation(){ 

int n, i=0; 
double x[100], y[100], s[100],a; 
cout << "Enter no. of sample points : \n"; 
cout << "\n"; 
cin >> n; 
cout << "\n"; 
cout << "Enter all values of x and corresponding functional value y : \n"; 
cout << "\n"; 
cout << "x | y \n"; 
for (i=0; i<n; i++){ 
    cin >> x[i] >> y[i]; 
} 
cout << "\n"; 
cout << "Enter the value of x for which you would like to calculate the estimated value of y : \n "; 
cout << "\n"; 
cin >> a; 
while (a<x[0] or a>x[n]){ 
    cout << "The selected value of x must belong to the domain [" << x[0] << "," << x[4] << "] \n" ; 
    cout << "\n"; 
    cout << "Reenter the value of x please : "; 
    cout << "\n"; 
    cin >> a; 
} 
cout << "\n"; 

for (i=0; i<n-1; i++){ 
    s[i]=y[i] + ((y[i+1]-y[i])/(x[i+1]-x[i]))*(a-x[i]); 
    if (a>=x[i] and a<=x[i+1]) 
     cout << "s[" << i << "] =" << s[i] << " when " << x[i] << " <= x <=" << x[i+1] <<endl; 

} 
return 0; 

}

x是數組

當過我的程序進入它從來沒有離開它

雖然環當我用常數切換x [0]和x [n]時,它可以完美運行

any ide如? 和感謝

+0

我的第一個猜測是某種隱式類型轉換出錯。你可以發佈更多的代碼,以便了解所涉及的一切類型嗎? –

+0

馬上......我會編輯帖子 –

+2

你從'x [0]'到'x [n-1]'有'n'個數字,所以'x [n]'在while循環只是一些隨機垃圾 –

回答

3

你以這種方式讀取:

for (i = 0; i < n; i++) { 
    cin >> x[i] >> y[i]; 
} 

數組x將在位置的值:[0,N-1]

但是,在這種同時:

while (a < x[0] or a > x[n]){ 

您試圖訪問數組的位置N,如果未初始化,它將是一個隨機數。