Chinaunix首页 | 论坛 | 博客
  • 博客访问: 235732
  • 博文数量: 37
  • 博客积分: 2259
  • 博客等级: 大尉
  • 技术积分: 365
  • 用 户 组: 普通用户
  • 注册时间: 2008-06-29 00:08
文章分类

全部博文(37)

文章存档

2009年(17)

2008年(20)

我的朋友

分类: 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.

阅读(1618) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~