全。我不确定在这里问这样一个‘简单’的问题是否合适,但实际上它对我来说很难:[,下面是这个问题和一些c代码:
main()
{
int c, i;
for (i = 0; (c = getchar()) != EOF && c != '\n'; ++i)
printf("%d", i);
if (c == '\n')
printf("%d", i);
}执行此程序后,当我输入"abc\n“时,程序将返回:
0
1
2
3我想知道为什么结果不是
0
1
2因为当c == '\n‘时,没有语句将i递增1。这就是我所想的,我一定是错了,你能告诉我我错在哪里吗?谢谢!
发布于 2011-04-23 14:35:20
for循环中的操作顺序为:
i = 0
(c = getchar()) != EOF && c != '\n' // c is set to 'a'
printf("%d", i) // displays 0
++i // i == 1
(c = getchar()) != EOF && c != '\n' // c is set to 'b'
printf("%d", i) // displays 1
++i // i == 2
(c = getchar()) != EOF && c != '\n' // c is set to 'c'
printf("%d", i) // displays 2
++i // i == 3
(c = getchar()) != EOF && c != '\n' // c is set to '\n'
// the loop exits因此,for循环之后的printf()输出i的最新值,即3。
发布于 2011-04-23 13:41:03
在c == '\n'用例之后执行++i。
也许这段代码会有助于澄清?
int i;
for (i = 0; i <= 3; ++i)
printf("%d\n", i);在循环结束时,i将是4,因为有了最后的增量。
发布于 2015-03-11 18:51:46
主要的问题是索引变量i的前增量,而不是前增量,在for loop.The中使用post增量,即i++,这背后的原因是前增量。当循环中的条件停止时,当您使用前增量时,i中存储的值已经是4。
main()
{
int c, i;
for (i = 0; (c = getchar()) != EOF && c != '\n'; i++)
printf("%d", i);
if (c == '\n')
printf("%d", i);
}https://stackoverflow.com/questions/5762429
复制相似问题