我只是想知道为什么
int i;
for (i=0; i<5; i++){
printf("%d\n",i)
}
printf("Here i get the result that misleads me : %d\n",i)最后一个值是5。
我的逻辑是:
From 0 to 4 -> printf
If i > 4 (since we are dealing with integers) stop the loop.但是循环停止在4,而不是5!为什么我在循环结束后得到5?为什么它会增加呢?
武断?
谢谢,
发布于 2013-11-30 15:43:11
for语句中有三个子句。
因此,每个for循环执行结束,执行增量操作,在第4次迭代中,i的值为5,而for循环在第5次迭代中的值为5。
发布于 2013-11-30 15:38:59
展开正在发生的事情
int i = 0;
while( i < 5 )
{
// body of for loop
i++;
}
// i == 5 here as i must be greater than or equal to 5 to break out of while loop发布于 2013-11-30 15:44:59
for循环是如何工作的:
for (initialization; condition; increment-decrement)
Statementi=0)i<5),如果为真,则跳到3其他跳转到5{ printf("%d\n",i) })i++),跳转到2在上一次迭代i == 4之前,它打印4,递增i。因此,在最后一次迭代i == 5后,!(5 < 5),即条件为false,退出循环。
https://stackoverflow.com/questions/20302035
复制相似问题