rand函数最大值为32768,取余100会生成0-99的随机数,再加上1就会生成1-100的随机数
rand函数和srand函数通常是一起使用的,rand控制随机数的取值范围,srand用时间控制生成伪随机数,srand返回的值必须是unsigned int
time函数是用来获取系统时间的,null--空指针
时间戳:当前计算机的时间-计算机的起始时间(1970.1.1 0:0:0)=(xxxxxx)秒
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
void menu()//显示菜单
{
printf("*****************************\n");
printf("***** 1.play 0.exit*****\n");
printf("*****************************\n");
}
void game()//游戏函数
{
int ret = 0;
int guess = 0;
ret = rand() % 100 + 1;//生成1-100之间的随机数
while (1)
{
printf("请输入数字");
scanf("%d", &guess);
if (guess > ret)
{
printf("猜大了");
}
else if (guess < ret)
{
printf("猜小了");
}
else
{
printf("猜对了");
break;
}
}
}
int main()
{
srand((unsigned int)time(NULL));//用时间来设置随机数
int input = 0;
do//使用dowhile先运行一次
{
menu();
printf("请选择");
scanf("%d", &input);
switch (input)
{
case 1:
game();
break;
case 0:
printf("退出游戏");
break;
default:
printf("选择错误");
break;
}
} while (input);//如果为1是真就循环,其他就结束
return 0;
}