首页 > 解决方案 > 在 C 编程语言中使用 do/while 时的奇怪输出

问题描述

我试图了解这个程序的输出。如果我尝试“翻译”代码,我相信它应该是这样的:

程序如何打印 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;
}

输出是:

哈哈哈哈嗨嗨嗨嗨嗬嗬嗬嗬

标签: cloopsdo-whilepost-incrementpre-increment

解决方案


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), jis 2, and ++jis3
  • 第二次迭代,3-2 = 1++j为 2。
  • 第三次迭代,2-2 = 0++j为 1。
  • 第四次迭代 ,1-2 = -1++j为 0 - 这使得whilechec 为假并且循环结束。

推荐阅读