分类: C/C++
2008-12-08 11:49:13
来自man srand的说明:
SYNOPSIS
#include
int rand(void);
void srand(unsigned int seed);
DESCRIPTION
The rand() function returns a pseudo-random integer between 0 and
RAND_MAX.
The srand() function sets its argument as the seed for a new sequence
of pseudo-random integers to be returned by rand(). These sequences
are repeatable by calling srand() with the same seed value.
If no seed value is provided, the rand() function is automatically
seeded with a value of 1.
RETURN VALUE
The rand() function returns a value between 0 and RAND_MAX. The
srand() returns no value.
Srand(0);
Rand();
这样每次产生的随机数序列都是一样的。正是man中所说的 repeatable 可重复性。因为计算机的随机数并不是真正的随机数,而是事先设定好的一个伪随机数序列,srand函数简单地说就是声明从序列的什么位置开始取数。一般情况下可以采用 当前时间相对于纪元时间的秒数来作为种子,即开始取数.这样就能取到不同的序列了。
注意一般不要将srand( (unsigned)time(NULL)) 放在循环里,因为速度太快,产生的随机数还是从同一个位置开始取的数,这样会取到几个相同的数。
如要取0-10的随机数可以 rand() % 10
来自 man 2 time 的说明:
SYNOPSIS
#include
time_t time(time_t *t);
DESCRIPTION
time returns the time since the Epoch (00:00:00 UTC, January 1, 1970),
measured in seconds.
If t is non-NULL, the return value is also stored in the memory pointed
to by t.
RETURN VALUE
On success, the value of time in seconds since the Epoch is returned.
On error, ((time_t)-1) is returned, and errno is set appropriately.