首页 > 解决方案 > C Primer Plus 中的 while2.c

问题描述

原代码如下:

#include <stdio.h>
int main(void)
{
    int n = 0;

    while (n++ < 3);
        printf("n is %d\n", n);

    return 0;
}

我想知道为什么结果是“n 是 4”而不是“n 是 3”?

标签: cwhile-loop

解决方案


这里发生的是你比较一个好的值,比如说 2 < 3,然后发生后增量,你最终在循环中得到 3

一个例子:

// you probably want to remove the ; at the end of the while like this:
while (n++ < 3) { // the posticrement will update the value n
    printf("n is %d\n", n); // here n will have an updated value
}

使用 {} 代替缩进也是一种很好的做法。


推荐阅读