c++ - while循环继续运行

标签 c++ arrays while-loop

所以这是我的代码片段:

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,如果未初始化,它将是一个随机数。

关于c++ - while循环继续运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30245304/

相关文章:

c++ - 使用多态指针调用函数

c - 将字符串存储在不规则数组中

ruby - 如何进一步分解数组中的字符串

XSLT 拆分大型单个父节点,分组为较小的子节点

java - 查找第二小整数时输出不正确

php - 停止 PHP while 循环然后继续吗?

c++ - boost 不相交集:如何检索集?

c++ - 在 C++ 中使用 malloc 后的行为

c++ - 在C++中排序后如何调用数组中的变量?

c++ - 需要帮助理解 C++ 中的运算符重载