1. rand函数
头文件 | stdlib.h |
原型 | int rand(void); |
说明 | 产生一个伪随机数 |
返回值 | 返回一个伪随机数 |
2. srand函数
头文件 | stdlib.h |
原型 | void srand(unsigned int seed); |
说明 | 设置随机数种子 |
返回值 | 无 |
3. time函数
头文件 | time.h |
原型 | time_t time(time_t* timer); |
说明 | 获取系统时间 |
返回值 | 返回Unix时间戳 |
4. 用法
- rand函数可以产生0-32767的随机数。
- rand函数每次调用前都会查询是否调用过srand函数,srand函数会设置供rand函数使用的随机数种子。如果种子没有变化,每次调用rand函数生成的伪随机数序列都是一样的。
- 当没有调用srand函数时,seed值默认为1,即当调用srand(1)时和没有调用srand函数时,rand函数产生的随机数序列相同。
- 如果要产生真正的随机数,通常以系统时间作为种子,即srand((unsigned int)time(NULL))。每次运行程序的时间肯定是不同的,产生的随机数序列肯定就不同。
- time(NULL)表示返回当前时间的Unix时间戳(Unix时间戳是指从1970年1月1日00时00分00秒开始所经过的秒数)。(unsigned int)time(NULL)表示将当前时间的Unix时间戳的time_t类型,强制类型转换为unsigned int类型。
- rand函数放在循环内,srand((unsigned int)time(NULL))放在循环外。
5. 猜数字游戏
设计一个猜数字游戏,游戏流程:
- 产生1-100的随机数
- 猜数字:猜大了或猜小了,直到猜对了,结束
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void menu()
{
printf("*****************************\n");
printf("******** 1. play ********\n");
printf("******** 0. exit ********\n");
printf("*****************************\n");
}
void game()
{
int guess = 0;
// 1. 生成1-100的随机数
int ret = rand() % 100 + 1; // rand()%100表示生成0-99的随机数,再+1表示生成1-100的随机数
// 2. 猜数字
while (1)
{
printf("请猜数字:>");
scanf("%d", &guess);
if (guess < ret)
{
printf("猜小了\n");
}
else if (guess > ret)
{
printf("猜大了\n");
}
else
{
printf("恭喜你,猜对了\n");
break;
}
}
}
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;
}