根据游戏要求,第一步就是先生成随机数,这里我们主要利用到三种函数 rand 、 srand 、 time 函数。所以下面依次介绍这三种函数。
int rand (void);
//rand 函数的使用需要包含一个头文件:stdlib.h
我们来看一段代码:
#include
#include
int main()
{
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n", rand());
return 0;
}
运行结果

分析:
rand 函数可以用来生成一个随机数,可惜是伪随机数,范围是在 0 ~ RAND_MAX 之间,RAND_MAX 大小依赖编译器实现,但大部分编译器是 32767。rand 函数是对一个叫”种子“的基准值进行运算生成的随机数。rand 函数生成随机数的默认种子是 1。那么怎么样才能让每一次运行的结果不一样呢?即每一次运行都产生不同的随机数。这是注意到上述代码中 rand 函数的种子没有变化,若让种子变化,那么每次是否就生成不同的随机数了?
void srand (unsigned int seed);
rand 函数之前先调用 srand 函数试试。srand 函数的参数 seed 来设置 rand 函数生成随机数的时候的种子,当种子发生变化,每次生成的随机数序列也就变化起来了。srand 函数是不需要频繁调用的,一次运行的程序中调用一次就够了。time_t time (time_t* timer);
// time 函数使用的时候需要包含头文件:time.h。
//如果只是让 `time` 函数返回时间戳,可以这样写
time (NULL); //调用 time 函数返回时间戳,这里没有接收返回值
time 函数会返回当前的日历时间,其实返回的是1970年1月1日0时0分0秒到现在程序运行时间之间的差值,单位是秒。
time_t 类型的,time_t 类型本质上其实就是32位或者64位的整型类型。time 函数的参数 timer
timer 指向的内存中带回去。time 函数返回的这个时间差也被叫做:时间戳。对上文代码进行优化
#include
#include
#include
int main()
{
srand((unsigned int) time (NULL));
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n", rand());
return 0;
}
运行结果

如果要生成 0~99 之间的随机数,方法如下:
rand() % 100; //余数的范围是0~99
既然随机数及其范围确定了,那么随机数生成的逻辑呢?
#include
#include
#include
void game()
{
int r = rand()%100;
int guess = 0;
while(1)
{
printf("请猜数字:>>>");
scanf("%d", &guess);
if (guess < r)
{
printf("猜小了\n");
}
else if(guess > r)
{
printf("猜大了\n");
}
else
{
printf("恭喜你,猜对了\n");
}
}
}
void menu()
{
printf("**************************************\n");
printf("**********欢迎来到猜数字游戏**********\n");
printf("**************************************\n");
printf("**********输入 1 --> 进入游戏*********\n");
printf("**************************************\n");
printf("**********输入 2 --> 退出游戏*********\n");
printf("**************************************\n");
printf("**************************************\n");
}
int main()
{
int input = 0;
srand((unsigned int) time(NULL));
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;
}