C语言中如何使用do-while语句

这篇文章给大家介绍C语言中如何使用do-while语句,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

成都创新互联公司是由多位在大型网络公司、广告设计公司的优秀设计人员和策划人员组成的一个具有丰富经验的团队,其中包括网站策划、网页美工、网站程序员、网页设计师、平面广告设计师、网络营销人员及形象策划。承接:成都网站设计、做网站、网站改版、网页设计制作、网站建设与维护、网络推广、数据库开发,以高性价比制作企业网站、行业门户平台等全方位的服务。

while循环和for循环都是入口条件循环,即在循环的每次迭代之前检查测试条件,所以有可能根本不执行循环体中的内容。C语言还有出口条件循环(exit-condition  loop),即在循环的每次迭代之后检查测试条件,这保证了至少执行循环体中的内容一次。这种循环被称为do while循环。

看下面的例子:

#include <stdio.h> int main(void) {     const int secret_code = 13;     int code_entered;      do     {         printf("To enter the triskaidekaphobia therapy club,\n");         printf("please enter the secret code number: ");         scanf("%d", &code_entered);     } while (code_entered != secret_code);     printf("Congratulations! You are cured!\n");      return 0; }

运行结果:

  • To enter the triskaidekaphobia therapy club,

  • please enter the secret code number: 12

  • To enter the triskaidekaphobia therapy club,

  • please enter the secret code number: 14

  • To enter the triskaidekaphobia therapy club,

  • please enter the secret code number: 13

  • Congratulations! You are cured!

使用while循环也能写出等价的程序,但是长一些,如程序清单6.16所示。

#include <stdio.h> int main(void) {     const int secret_code = 13;     int code_entered;      printf("To enter the triskaidekaphobia therapy club,\n");     printf("please enter the secret code number: ");     scanf("%d", &code_entered);     while (code_entered != secret_code)     {         printf("To enter the triskaidekaphobia therapy club,\n");         printf("please enter the secret code number: ");         scanf("%d", &code_entered);     }     printf("Congratulations! You are cured!\n");      return 0; }

下面是do while循环的通用形式:

do     statement while ( expression );

statement可以是一条简单语句或复合语句。注意,do-while循环以分号结尾。

C语言中如何使用do-while语句
Structure of a =do while= loop=

do-while循环在执行完循环体后才执行测试条件,所以至少执行循环体一次;而for循环或while循环都是在执行循环体之前先执行测试条件。do  while循环适用于那些至少要迭代一次的循环。例如,下面是一个包含do while循环的密码程序伪代码:

do {     prompt for password     read user input } while (input not equal to password);

避免使用这种形式的do-while结构:

do {    ask user if he or she wants to continue    some clever stuff } while (answer is yes);

这样的结构导致用户在回答“no”之后,仍然执行“其他行为”部分,因为测试条件执行晚了。

关于C语言中如何使用do-while语句就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

当前文章:C语言中如何使用do-while语句
URL标题:https://www.cdcxhl.com/article30/jgeppo.html

成都网站建设公司_创新互联,为您提供做网站网站排名营销型网站建设微信小程序网站导航微信公众号

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都做网站