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

avatar
作者
筋斗云
阅读量:0

以下是一个简单的猜数字小游戏的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之间的随机数作为目标数字,然后提示玩家猜数字,并根据玩家的猜测给出提示,直到玩家猜对为止。在游戏过程中会统计玩家猜测的次数。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!