温馨提示×

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

小亿
82
2024-03-08 15:00:25
栏目: 编程语言

以下是一个简单的猜数字小游戏的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("欢迎来到猜数字小游戏!\n");
    printf("游戏规则:请猜一个1到100之间的数字\n");

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

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

    return 0;
}

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

0