循环保持运行

while loop keeps running

本文关键字:运行 环保 循环      更新时间:2023-10-16

所以这是我的代码段:

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]时,它运行完美

有什么想法吗?谢谢

您正在以这种方式阅读:

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

数组x在位置中的值:[0,n-1]

但在此时:

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

您尝试访问数组的位置n,如果不初始化,这将是一个随机数。