【问题标题】:while loop keeps runningwhile循环继续运行
【发布时间】:2015-07-26 12:57:38
【问题描述】:

这是我的代码 sn-p :

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

有什么想法吗? 并感谢

【问题讨论】:

  • 我的第一个猜测是某种隐式类型转换出错了。您能否发布更多代码,以便了解所涉及的所有内容的类型?
  • 马上......我会编辑帖子
  • 数组中有n 数字,从x[0]x[n-1],所以while 循环中的x[n] 只是一些随机垃圾
  • @MateuszKacprzak 不错的收获

标签: c++ arrays while-loop


【解决方案1】:

你是这样阅读的:

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

数组 x 将在以下位置有值:[0, N-1]

但是在这个时候:

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

你试图访问数组的位置 N,如果没有初始化,它将是一个随机数。

【讨论】:

    猜你喜欢
    • 2019-02-26
    • 1970-01-01
    • 2014-03-11
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 2020-06-09
    相关资源
    最近更新 更多