1. int rand(void) 函数的头文件<stdlib.h>
// Len_rand.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdlib.h>
int _tmain(int argc, _TCHAR* argv[])
{
int count = 0;
while (count<5)
{
int ran = rand();
printf("ran: %d \n",ran);
count++;
}
return 0;
}
2. 执行结果发现,每次执行程序生成的随机数都是固定的
3. 解决这个问题我需要引入一个【随机数种子】的概念
为什么要引入时间种子:
首先我们要知道,计算机不能产生绝对的随机数。
只能产生伪随机数,也就是有规律的意思。
伪随机数就是计算机产生的随机数是有规律的。
计算机产生随机数是通过算法,这个算法是有映射关系的,如我放进去它会出来一个特定的数。
我们把这个算法看成是一个黑盒子,放进一个数,就会出来一个特定的数,
并把这个数当做下一次的种子再放进去。
系统实现随机数是把当前的系统时间放进去,系统时间是一直在往前走的,
每次都不一样,所以可以实现每次得到的随机数都不一样的效果。
4. 添加时间种子,以及头文件<time.h>
#include "stdafx.h"
#include <stdlib.h> // rand()函数需要用到的头文件
#include <time.h> // 时间种子需要用到的头文件
int _tmain(int argc, _TCHAR* argv[])
{
// 添加时间种子
srand((unsigned)time(NULL));
int count = 0;
while (count<5)
{
// 调用随机函数
int ran = rand();
printf("ran: %d \n",ran);
count++;
}
return 0;
}
5. 执行多次程序,获取不同的随机数