热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

这个程序如何最终获得5分?

有人可以解释这个程序吗?末尾如何打印“5”?预先感谢。#include<stdio.h>#inc

有人可以解释这个程序吗?末尾如何打印“ 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

这将在每次检查时打印该值,在之前将其增加。基本上,两个循环都必须在值超出范围时第一次检查该值,然后在值超出范围时第二次检查该值。

请注意,在同一表达式中将++与其他运算符混合使用是不好的做法。上面是一些繁琐的人工代码,仅用于说明执行路径。


推荐阅读
author-avatar
MySeptember
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有