作者:MySeptember | 来源:互联网 | 2023-09-12 09:52
有人可以解释这个程序吗?末尾如何打印“ 5”?预先感谢。
#include
#include
int main()
{
int a = 1;
while (a++ <= 1)
while (a++ <= 2);
printf("%d",a); //5
return 0;
}
请注意,在第一个while语句之后没有;
。这意味着有嵌套的while循环。
while (a++ <= 1)
while (a++ <= 2);
让我们一一检查一下这些行。
a = 1; // initialize
while (a++ <= 1) // condition is TRUE,after this statement a === 2
while (a++ <= 2); // condition is TRUE,after this a == 3
while (a++ <= 2); // condition is FALSE,// but `a++` is still evaluated. So after this statement a == 4.
// Inner loop exits
while (a++ <= 1) // condition is FALSE,// `a++` is evaluated and after this a==5
// Outer Loop exits
printf("%d",a); // print value of a i.e. print 5.
,
在第一个被检查的值是1时,它将增加1
然后进入下一个,在那里它是2,所以2
,
a = 1; First iteration Second iteration
while (a++ <= 1) { (1 <= 1) True (4 <= 1) Fail
(a = a + 1) == 2 (a = a + 1) == 5
while (a++ <= 2) { }; (a == 2) <= 2 True
(a == 3) first time
(a == 4) When while evalutes to fail
}
,
如果出于未知原因您无法在查看变量时使用调试器和单个步骤,则可以在此过程中添加一些printf调试代码。并在缩进时修复缩进:
#include
int main()
{
int a = 1;
while (printf("Outer while %d\n",a),a++ <= 1)
while (printf("Inner while %d\n",a++ <= 2)
;
printf("Result %d\n",a);
return 0;
}
输出:
Outer while 1
Inner while 2
Inner while 3
Outer while 4
Result 5
这将在每次检查时打印该值,在之前将其增加。基本上,两个循环都必须在值超出范围时第一次检查该值,然后在值超出范围时第二次检查该值。
请注意,在同一表达式中将++与其他运算符混合使用是不好的做法。上面是一些繁琐的人工代码,仅用于说明执行路径。