gpt4 book ai didi

C语言中do-while语句的2种写法示例

转载 作者:qq735679552 更新时间:2022-09-29 22:32:09 24 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章C语言中do-while语句的2种写法示例由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

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

看下面的例子:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#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所示.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#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循环的通用形式:

?
1
2
3
do
  statement
while ( expression );

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

C语言中do-while语句的2种写法示例

Structure of a =do while= loop= 。

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

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

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

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

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

总结 。

到此这篇关于C语言中do-while语句的2种写法的文章就介绍到这了,更多相关C语言do-while语句写法内容请搜索我以前的文章或继续浏览下面的相关文章希望大家以后多多支持我! 。

原文链接:https://www.toutiao.com/a6852114155407671820/ 。

最后此篇关于C语言中do-while语句的2种写法示例的文章就讲到这里了,如果你想了解更多关于C语言中do-while语句的2种写法示例的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com