gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:11:45 25 4
gpt4 key购买 nike

我编写了一个程序,它从用户那里接受一个值,然后在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com