rand和srand是用于产生伪随机数的两个函数,根据参考手册rand的返回值是在[0, RAND_MAX]之间的数据,RAND_MAX在不同的系统中数值有所不同。
以下是rand和srand实现方式的一个示例(假定RAND_MAX为32767)
static unsigned long next = 1;
/* RAND_MAX assumed to be 32767 */
int rand(void) {
next = next * 1103515245 + 12345;
return((unsigned)(next/65536) % 32768);
}
void srand(unsigned seed) {
next = seed;
}
事实上现在多数系统上的rand和srand就是使用的这种机制,只是上面取的数字或略有不同。
#include
#include
int main()
{
int i;
for (i = 0; i < 10; i++)
{
printf("%d ", rand());
}
getchar();
return 0;
}
41 18467 6334 26500 19169 15724 11478 29358 26962 24464
但是,当我们再运行一次时,我们会发现产生的序列是相同的。在当我们需要每次运行都产生不同的序列时,上面这样的函数显然是不行的。这是要注意的第一个陷阱。
在Linux下编译上面的程序,两次运行也会得出相同的结果,这与我们程序代码的预期是相同的。如果我们在程序的循环之前添加srand(1),我们会得到相同的序列(与不调用srand效果相同)
根据实现机制给出的代码,如果我们写的程序是如下:
#include
#include
int main()
{
int i;
for (i = 0; i < 10; i++)
{
srand(1);
printf("%d ", rand());
}
getchar();
return 0;
}
那它输出的序列将是相同的数,经过实际测试,确实如此:
41 41 41 41 41 41 41 41 41 41
如何写出每次运行结果都不同的随机序列呢?我们来看下例:
#include
#include
#include
int main()
{
int i;
srand(time(NULL));
for (i = 0; i < 10; i++)
{
printf("%d ", rand());
}
getchar();
return 0;
}
所以在这种情况下,最好用能取到毫秒和微秒级系统时间的函数去改写上面程序,并且在取到数时,先取一次模,再将数字拿去做种子会比较可靠一些。
如下面在Linux下的一个实现方法:
#include
#include
#include
#include
int main()
{
int i, seed;
struct timeval tv;
struct timezone tz = {0, 0};
gettimeofday(&tv, &tz);
/* tv.tv_usec 是一个微秒级的时间 */
seed = tv.tv_usec % 65536;
srand(seed);
for (i = 0; i < 10; i++)
{
printf("%d ", rand());
}
getchar();
return 0;
}
这个版本的运行结果基本可以满足预期,都是不相同的序列,即使在fork多个进程运行时,也可以使每个进程所得到的序列是不相同的。