新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

C语言怎么实现猜数字小游戏,C语言怎么实现逆序输出字符串

发布时间:2024-03-08 15:00:25

C语言怎样实现猜数字小游戏

以下是一个简单的猜数字小游戏的C语言实现示例:

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

int main() {
    int target, guess, attempts = 0;

    // 生成随机数作为目标数字
    srand(time(0));
    target = rand() % 100 + 1;

    printf("欢迎来到猜数字小游戏!
");
    printf("游戏规则:请猜一个1到100之间的数字
");

    do {
        printf("请输入你的猜想:");
        scanf("%d", &guess);
        attempts++;

        if (guess < target) {
            printf("你猜的数字太小了,请再试一次。
");
        } else if (guess > target) {
            printf("你猜的数字太大了,请再试一次。
");
        } else {
            printf("恭喜你猜对了!你用了 %d 次猜对了数字 %d。
", attempts, target);
        }
    } while (guess != target);

    return 0;
}

这段代码会生成一个1到100之间的随机数作为目标数字,然后提示玩家猜数字,并根据玩家的猜想给出提示,直到玩家猜对为止。在游戏进程中会统计玩家猜想的次数。