srand()、rand()、time()函数的用法

srand()就是给rand()提供种子seed。

如果srand每次输入的数值是一样的,那么每次运行产生的随机数也是一样的。

以一个固定的数值作为种子是一个缺点。通常的做法是 :以这样一句srand((unsigned) time(NULL));来取代,这样将使得种子为一个不固定的数,这样产生的随机数就不会每次执行都一样了。详细用法如下:

 1 #include <iostream>
 2 #include <stdlib.h>
 3 #include <time.h>
 4 using namespace std;
 5 int main()
 6 {
 7     /*Seed the random-number generator with current time 
 8     so that the numbers will be different every time we run.*/
 9     srand((unsigned)time(NULL));
10     
11     /* Display 10 numbers */
12     for(int i=0;i<10;i++)
13     {
14         cout<<rand()<<endl;
15     }
16     return 0;
17 }

 

rand(void)用于产生一个伪随机unsigned int 整数。 
srand(seed)用于给rand()函数设定种子。

srand 和 rand 应该组合使用。一般来说,srand 用于对 rand 进行设置。 
比如:

#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int main()
{
    srand(time(0));
    /* Display 10 numbers */
    for(int i=0;i<10;i++)
    {
        cout<<rand()%100<<endl;
    }
    return 0;
}

 

posted @ 2016-11-06 15:12  add_oil  阅读(6129)  评论(0编辑  收藏  举报