c - 在 C 编程语言中使用 do/while 时的奇怪输出
问题描述
我试图了解这个程序的输出。如果我尝试“翻译”代码,我相信它应该是这样的:
- 而“j”小于 3 - 打印“Ha”(这个循环执行 3 次,所以它给出 3 个“Ha”)
- do/while -> j 等于 j - 2 因此打印 "Hi" 而 ++j - 最后程序打印出 "Hi" 4 次。
程序如何打印 4 次,这里的条件如何工作?
#include <stdio.h>
int main() {
int j = 0;
while(j++ < 3){
printf( "Ha ");
}
do{
j -= 2;
printf( "Hi ");
}
while(++j);
for(j = 1; j <= 3; j++){
printf( "Ho ");
}
printf("\n");
return 0;
}
输出是:
哈哈哈哈嗨嗨嗨嗨嗬嗬嗬嗬
解决方案
is 前缀增量,即该++j
值将增加,然后,增加的值将用于条件检查。
为了便于理解,我添加了打印声明:
do{
j -= 2;
printf( "Hi ");
printf("value of j before the while = %d\n", j);
}
while(++j);
输出是:
Hi value of j before the while = 2
Hi value of j before the while = 1
Hi value of j before the while = 0
Hi value of j before the while = -1
所以,在
- 第一次迭代, in
while (++j)
,j
is2
, and++j
is3
- 第二次迭代,
3-2 = 1
和++j
为 2。 - 第三次迭代,
2-2 = 0
和++j
为 1。 - 第四次迭代 ,
1-2 = -1
和++j
为 0 - 这使得while
chec 为假并且循环结束。
推荐阅读
- javascript - 如何获取所选文本输入的前后
- python - 删除二维数组中的零行和列
- powershell - 通过 PowerShell 部署时,如何将共享数据源绑定到共享数据集?
- javascript - Firebase .OrderByChild() 不适用于布尔值
- database - 在VBA(Access)中独立地重新查询表单的多个实例
- c - 我应该在中断程序中检索 SPI 数据吗?
- python - 声明性基础不收集表格
- listview - ExpansionTile 内的 ListView 不起作用
- go - sync.Waitgroup 不会阻止执行
- python - 正则表达式仅匹配用逗号分隔的唯一名称