c语言怎么做猜数字游戏

2025-03-10 01:48:54

1、先打开IDE,创建一个c语言项目,我这里使用的是CLion+CMake来创建

c语言怎么做猜数字游戏

2、编写欢迎界面,代码如图

c语言怎么做猜数字游戏

3、接着编写我们的handle_user_input函数用来处理用户的输入

c语言怎么做猜数字游戏

4、然后编写我们的游戏主程序

c语言怎么做猜数字游戏

5、最后编写我们游戏逻辑

c语言怎么做猜数字游戏
c语言怎么做猜数字游戏
c语言怎么做猜数字游戏

6、最后来测试一下我们的游戏,可以看到冤铘讵柘没有大问题了,可能其中还有些许的小bug,有兴趣的同学可以自己多玩玩,出现bug自己尝试调试,这也是一个难得的学习过程哦

c语言怎么做猜数字游戏

7、这里把完整的代码贴出来://// Created by steve on 19-2-22.//#include <stdio.h>稆糨孝汶;#include <stdlib.h>#define RANGE 100void play_game();void welcome() { printf("欢迎来到猜数字游戏!\n"); printf("\tq/Q\t退出游戏\n"); printf("\ts/S\t开始游戏\n");}void handle_user_input() { char input; scanf("%c", &input); switch (input) { case 'q': case 'Q': exit(0); case 's': case 'S': //开始游戏 play_game(); break; default: break; }}void play_game() { printf("请在0-%d之间猜出系统指定的数:\n", RANGE-1); int input; int times = 0; int answer = rand() % RANGE; while (1) { scanf("%d", &input); times++; if (input == answer) { printf("答对啦!一共猜了%d次\n", times); break; } if (input < answer){ printf("答案比%d大哦!\n",input); } else{ printf("答案比%d小哦!\n",input); } }}int main() { while (1){ welcome(); handle_user_input(); } return 0;}

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢