1

逍遥自在学C语言 | 揭开while循环的神秘面纱 - 知微之见

 11 months ago
source link: https://www.cnblogs.com/Wayne123/p/17441803.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

循环是一种重要的控制结构,可以使程序重复执行一段代码,直到满足特定条件为止。
在C语言中,while和do-while是两种常用的循环结构,本文将详细介绍这两种循环的用法。

一、人物简介

  • 第一位闪亮登场,有请今后会一直教我们C语言的老师 —— 自在。
img
  • 第二位上场的是和我们一起学习的小白程序猿 —— 逍遥。
img

二、基本语法

让我们先揭开While循环的神秘面纱,它的基本语法如下:

while (条件) 
{
    // 循环体
}

这个条件就像是一道门卫,只有条件为真时,我们才能进入循环体。当条件为假时,门卫会善意地告诉我们:“你们可以离开了,我不会阻挡你们继续前进。”

三、while和do-while

while循环:它是最常见的循环方式,先判断条件是否满足,如果满足就进入循环体。

我们可以像玩过山车一样刺激地循环,直到条件不满足才停下来。

int count = 0;
while (count < 5) 
{
    printf("如果感到快乐你就拍拍手!\n");
    count++;
}

do-while循环:它比较乐观,先执行一次循环体,然后再判断条件。

只要条件满足,我们就可以快乐地重复执行循环体,直到条件不满足为止。

int number;
do 
{
    printf("请输入一个正整数:");
    scanf("%d", &number);
} while (number <= 0);

四、while和do while循环的应用

场景一:冒险者的征程

#include <stdio.h>
int main() 
{
    int health = 100;
    while (health > 0) 
    {
        printf("勇敢的冒险者,你的生命值还剩下 %d\n", health);
        health -= 10;
        printf("你被怪物攻击了!生命值减少 10\n");
    }
    printf("很遗憾,你的冒险结束了!\n");
    return 0;
}
1511464-20230529220140160-920973408.png

场景二:猜大小

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    int targetNumber, guess;
    srand(time(NULL));  // 设置随机数种子

    // 生成1到100之间的随机数
    targetNumber = rand() % 100 + 1;

    printf("猜数字游戏开始!\n");

    do {
        printf("请输入一个1到100之间的整数:");
        scanf("%d", &guess);

        if (guess == targetNumber) {
            printf("恭喜你猜对了!\n");
        } else if (guess < targetNumber) {
            printf("猜小了,请继续尝试!\n");
        } else {
            printf("猜大了,请继续尝试!\n");
        }
    } while (guess != targetNumber);

    printf("游戏结束!\n");

    return 0;
}
1511464-20230529220154399-632264150.png

通过这篇文章,我们学会了

1、while 循环的用法

2、do- while 循环的用法

📢欢迎各位 👍点赞 ⭐收藏 📝评论,如有错误请留言指正,非常感谢!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK