当前位置:网站首页>关于猜数字游戏的实现
关于猜数字游戏的实现
2022-06-25 12:35:00 【LIn_jt】
关于简易猜数字游戏的实现
对于今天的三子棋游戏,有以下几个特性:
- 玩家通过输入数字来选择是否进行游戏或退出游戏,选错时会提示并重新输入
- 通过键盘输入数据后,电脑会提示玩家所猜的数据过大或过小,若猜对则打印恭喜你,猜对了,然后让玩家重新选择是否重新进行游戏
- 随机数的范围为1-100
废话不多说,直接上代码:>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void menu()
{
printf("**********************\n");
printf("****** 1.play *******\n");
printf("****** 0.exit *******\n");
printf("**********************\n");
}
void game()
{
int input2 = 0;
int ret = rand() % 100 + 1;//生成一个随机数;
while (1)
{
printf("请猜数字:>");
scanf("%d", &input2);
if (input2 < ret)
{
printf("猜小了\n");
}
else if (input2 > ret)
{
printf("猜大了\n");
}
else
{
printf("恭喜你,猜对了\n");
break;
}
}
}
int main()
{
int input1 = 0;
srand((unsigned int)time(NULL));//设置随机数的起点
do
{
menu();//此处的menu为菜单函数
printf("请输入数字:>");
scanf("%d", &input1);
switch(input1)
{
case 1:
printf("猜数字游戏\n");
game();
break;
case 0:
printf("退出程序\n");
break;
default:
printf("输入错误,请重新输入\n");
break;
}
} while (input1);
return 0;
}
各处代码讲解

关于主函数中的srand函数,为设置一个随机数起点,但若要生成一个随机数,还需要给他传一个随机数,因此,我们想到了用时间来作为参数,并且强制转换为(unsigned int)类型,来匹配srand的语法。
menu为我们自己创建的菜单函数,用来输出并提示玩家要输入什么

关于do-while循环:

因为游戏至少执行一次,因此用do while循环来进行切入,其中的switch case用来判断玩家输入为几来执行相应的结果
若选1.则进行游戏,若选0,则退出游戏,若选择其他数字,则重新输入
对game函数的讲解:

game函数中,rand函数用来生成一个随机数,在while循环中,玩家输入的数字会与rand函数产生的随机数进行比较,如果输入过小或过大,电脑都会进行提示,让玩家重新输入,若玩家猜对,则跳出循环,让玩家重新开始游戏或退出程序。
对于程序的一点变动

前面所打印的内容占了一部分屏幕,看起来好像不太爽,因此对程序进行以下改动:



这样的话打印出来会变得漂亮一些(我个人是这么认为的)!。
边栏推荐
- 深圳民太安智能二面_秋招第一份offer
- WIN10环境下配置pytorch
- . NET in China - What's New in . NET
- KVM 脚本管理 —— 筑梦之路
- 二叉树之_哈夫曼树_哈弗曼编码
- Stockage des données en mémoire
- LeetCode链表题解技巧归纳总结
- AGCO AI frontier promotion (6.25)
- 關於數據在內存中的存儲下
- Heavyweight live | bizdevops: the way to break the technology situation under the tide of digital transformation
猜你喜欢
随机推荐
Pointer, it has to say that the subject
剑指 Offer II 032. 有效的变位词
Always maintain epidemic prevention and control and create a safe and stable social environment
Golang keyboard input statement scanln scanf code example
Update PIP & Download jupyter Lab
Resolution of PPT paper drawing
MySQL adds, modifies, and deletes table fields, field data types, and lengths (with various actual case statements)
Detailed explanation of string operation functions and memory functions
Spoken English - weak reading
An article clearly explains MySQL's clustering / Federation / coverage index, back to table, and index push down
數據在內存中的存儲相關內容
汇编标志位相关知识点(连)
QT mouse tracking
golang键盘输入语句scanln scanf代码示例
torch. Tensor splicing and list (tensors)
Sword finger offer day 2 linked list (simple)
Summary of leetcode linked list problem solving skills
重磅直播|BizDevOps:数字化转型浪潮下的技术破局之路
[pit avoidance means "difficult"] actionref current. Reload() does not take effect
药物设计新福音:腾讯联合中科大、浙大开发自适应图学习方法,预测分子相互作用及分子性质




![[visio] solving the fuzzy problem of parallelogram in word](/img/04/8a1de2983d648e67f823b5d973c003.png)



