先看代码
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void game()
{
int guess = 0;
int ret = rand() % 100 + 1;//%100的作用是为了让生成的数字范围在0--99
while (1)
{
printf("猜的数字:");
scanf("%d", &guess);
if (guess > ret) printf("数字大了\n");
else if (guess < ret) printf("数字小了\n");
else
{
printf("恭喜老铁,你猜对了\n");
break;
}
}
}
void menu()
{
printf("************************************\n");
printf("******* 1.play ***********\n");
printf("******* 0.exit ***********\n");
printf("************************************\n");
}
int main()
{
//利用函数rand需要使用,srand只需要使用一次,放在主函数里面就可以
//这是设置随机数的生成器
srand ((unsigned int)time(NULL));
int input = 0;
do
{
menu();
printf("请选择是否要玩游戏:>");
scanf("%d", &input);
switch (input)
{
case 1:
game();
break;
case 0:
printf("退出程序\n");
break;
default:
printf("选择错误,请重新选择\n");
break;
}
} while (input);
return 0;
}
int ret=rand() 此时ret就是随机数,但是使用rand函数需要先用srand
srand ((unsigned int)time(NULL)); ,记住这个用法就可以 不需要深究
time的头文件<time.h> rand和srand的头文件是<stdlib.h>
这篇博客介绍了一个简单的C语言实现的猜数字游戏,游戏数字范围为1到100。用户通过输入猜测,系统会提示数字大小。此外,还包含一个菜单选择系统,允许用户选择继续游戏或退出程序。程序使用`srand`和`rand`函数生成随机数,并依赖`time.h`和`stdlib.h`库。
4851

被折叠的 条评论
为什么被折叠?



