简体   繁体   English

for 循环接受一个比循环条件额外的值

[英]for loop accepts one extra value than the loop condition

I have written a program which accepts a value from a user and then iterates over that value in a for loop.我编写了一个程序,它接受来自用户的值,然后在 for 循环中迭代该值。 in for loop I accept numbers to be stored in the array.在 for 循环中,我接受要存储在数组中的数字。 My problem is for loop accepts one extra value than specified by user.我的问题是 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;
  }
}

if the user enters 3 it should accept 3 values if如果用户输入 3,则应接受 3 个值,如果

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

if the user enters 3 it should accept 4 values if如果用户输入 3 它应该接受 4 个值如果

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

Indexes in C go from 0..n-1 . C 中的索引从0..n-1 In your for loop you go from 0..n and that is one too many.在您的 for 循环中,您从0..n ,这太多了。 Change改变

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

to

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

A space in the scanf format matches any white-space, and any number of consecutive white-space. scanf格式中的空格匹配任何空格和任意数量的连续空格。

The problem with a trailing space is that then scanf must continue reading until it reads something that isn't a white-space, otherwise it doesn't know when the spaces ends.尾随空格的问题是scanf必须继续读取,直到读取到不是空白的内容,否则它不知道空格何时结束。

That leads to the problem that you need to give some extra non white-space input.这导致您需要提供一些额外的非空白输入的问题。

For all but two formats ( "%c" and "%[" ) the scanf function automatically reads and discards leading white-space.对于除两种格式( "%c""%[" )之外的所有格式, scanf函数会自动读取并丢弃前导空格。 So it's usually not needed to include spaces in a format string.所以通常不需要在格式字符串中包含空格。 Except perhaps for those two formats that doesn't skip white-space.除了这两种不跳过空格的格式。

Read eg this scanf (and family) reference for more details.阅读例如scanf (和系列)参考以了解更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM