C语言的do-while语句的两种写法

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

看下面的例子:

 
 
 
  1. #include  
  2. int main(void) 
  3.     const int secret_code = 13; 
  4.     int code_entered; 
  5.  
  6.     do 
  7.     { 
  8.         printf("To enter the triskaidekaphobia therapy club,\n"); 
  9.         printf("please enter the secret code number: "); 
  10.         scanf("%d", &code_entered); 
  11.     } while (code_entered != secret_code); 
  12.     printf("Congratulations! You are cured!\n"); 
  13.  
  14.     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所示。

 
 
 
  1. #include  
  2. int main(void) 
  3.     const int secret_code = 13; 
  4.     int code_entered; 
  5.  
  6.     printf("To enter the triskaidekaphobia therapy club,\n"); 
  7.     printf("please enter the secret code number: "); 
  8.     scanf("%d", &code_entered); 
  9.     while (code_entered != secret_code) 
  10.     { 
  11.         printf("To enter the triskaidekaphobia therapy club,\n"); 
  12.         printf("please enter the secret code number: "); 
  13.         scanf("%d", &code_entered); 
  14.     } 
  15.     printf("Congratulations! You are cured!\n"); 
  16.  
  17.     return 0; 

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

 
 
 
  1. do 
  2.     statement 
  3. while ( expression ); 

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

Structure of a =do while= loop=

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

 
 
 
  1. do 
  2.     prompt for password 
  3.     read user input 
  4. } while (input not equal to password); 

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

 
 
 
  1. do 
  2.    ask user if he or she wants to continue 
  3.    some clever stuff 
  4. } while (answer is yes); 

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

分享标题:C语言的do-while语句的两种写法
URL地址:http://www.csdahua.cn/qtweb/news20/370520.html

网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

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