【发布时间】:2019-04-14 10:09:12
【问题描述】:
我编写了一个程序,它接受来自用户的值,然后在 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 个值
for (i = 0; i<no_of_boxcars;++i)
{
//but here accepts 4 values
}
如果用户输入 3,它应该接受 4 个值
for (i = 0; i<=no_of_boxcars;++i)
{
//and here accepts 5 values
}
【问题讨论】:
-
"一个额外的值":
<与<=不同。 -
对于
no_of_boxcars等于3,这个循环for (i = 0; i < no_of_boxcars; ++i) { ...}正好重复三次。 -
@xing,谢谢你是对的,这就是问题所在。我现在工作
-
@alk,是的,你是对的,它们不一样,但我的问题是我的循环接受了一个超出预期的额外值。因此,如果我从“%lf”中删除尾随空格,那么它的工作就完美了。