c - 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”?
解决方案
这里发生的是你比较一个好的值,比如说 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
}
使用 {} 代替缩进也是一种很好的做法。
推荐阅读
- intellij-idea - 如何为 intellij 正确设置 adb/PATH
- typescript - 要联合的类数组(反之亦然)
- java - 当字符属性更改时,Java JTextPane 不会更新其大小
- bash - 使用 sudo 和 awk 进行 Bash while 循环
- python - 是否可以在 PysimpleGui 表中插入复选框?
- microsoft-graph-api - 从 Teams 获取活跃的 PSTN 来电显示
- android - 在推送通知中显示视频、gif 或横幅
- c - POSIX 的 FTW 结构成员 - 他们告诉我们什么?
- asterisk - 当我在 Asterisk 中拨打任何分机时,首先播放一些问候消息?
- c++ - 对话关闭信号