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

C语言的do-while语句的两种写法带轴承的技术图纸和卡尺while循环和for循环都是入口条件循环,即在循环的每次迭代之前检查测试条件,所以有可能根本不执行循环体中的内容。C语言

大家好,欢迎来到IT知识分享网。

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”之后,仍然执行“其他行为”部分,因为测试条件执行晚了。

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/53003.html

(0)
上一篇 2024-08-08 21:15
下一篇 2024-08-09 17:33

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信