c - for 循环接受比循环条件多一个值

标签 c arrays for-loop scanf

我编写了一个程序,它从用户那里接受一个值,然后在 for 循环中迭代该值。在 for 循环中,我接受要存储在数组中的数字。 我的问题是 for 循环接受一个比用户指定的额外值。

int main()
{
  int  i = 0;
  int  a;
  int no_of_boxcars = 0;
  double array[10];
  double boxcart_wt = 0;
  //printf("Enter the no of wagons");
  scanf_s("%d", &no_of_boxcars);        // no of boxcars
  for (i = 0; i<=no_of_boxcars;++i)
  {
    printf("%d \t", i);
    scanf_s("%lf ", &boxcart_wt);   //weight in boxcar

    array[i] = boxcart_wt;
  }
}

如果用户输入 3 它应该接受 3 个值 if

for (i = 0; i<no_of_boxcars;++i)
{
  //but here accepts 4 values
}

如果用户输入 3 它应该接受 4 个值 if

for (i = 0; i<=no_of_boxcars;++i)
{
  //and here accepts 5 values
}

最佳答案

C 中的索引从 0..n-1 开始。在您的 for 循环中,您从 0..n 开始,这太多了。变化

for (i = 0; i<=no_of_boxcars;++i)

for (i = 0; i<no_of_boxcars;++i)

关于c - for 循环接受比循环条件多一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55674090/

相关文章:

ios - 如何在 swift 中创建一个由类实例填充的数组?

c - 动态生成的代码在错误的地址执行

c - C中过程的使用

c++ - HashMap 以找到添加到给定总和的一对

c - 需要指针帮助

C++ - 如何初始化原子数组?

java图像不显示

javascript - Google Apps 脚本事件 EventGuest 没有 .getEmail()

c - 为什么会发生段错误以及我们如何避免这种情况?

c - 小费计算——将一个数字换成小数表示