资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

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

本篇内容主要讲解“C语言的do-while语句如何使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C语言的do-while语句如何使用”吧!

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:国际域名空间、网页空间、营销软件、网站建设、温岭网站维护、网站推广。

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

看下面的例子:

#include  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  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循环以分号结尾。

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:http://cdkjz.cn/article/jgdehg.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220