所以这是我的代码段:
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]时它完全运行
任何想法? 并谢谢
答案 0 :(得分: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,如果没有初始化,它将是一个随机数。