How to implement a number guessing game in C language?

Here is an example of a simple number guessing game implemented in the C programming language.

#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;
}

This code will generate a random number between 1 and 100 as the target number, prompt the player to guess the number, give hints based on the player’s guesses, and continue until the player guesses correctly. The game will also keep track of how many times the player guesses.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds