温馨提示×

c语言怎么实现猜数字游戏程序

小亿
82
2024-06-07 10:41:23
栏目: 编程语言

下面是一个简单的猜数字游戏程序的示例:

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

int main() {
    int number, guess, attempts = 0;
    
    // 生成一个1到100的随机数
    srand(time(0));
    number = rand() % 100 + 1;
    
    printf("欢迎来到猜数字游戏!\n");
    
    do {
        printf("请输入一个1到100之间的数字猜猜看:");
        scanf("%d", &guess);
        
        attempts++;
        
        if (guess > number) {
            printf("猜的数字太大了,请再试一次\n");
        } else if (guess < number) {
            printf("猜的数字太小了,请再试一次\n");
        } else {
            printf("恭喜你猜对了!你用了 %d 次尝试\n", attempts);
        }
    } while (guess != number);
    
    return 0;
}

这个程序首先生成一个1到100之间的随机数,然后要求用户猜这个数字,直到猜对为止。程序会根据用户每次猜测的数字给出相应的提示,直到用户猜对为止。最后程序会显示用户猜对的次数。

0