
正文
srand()、rand()、time()函数的用法
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
srand()就是给rand()提供种子seed。
如果srand每次输入的数值是一样的,那么每次运行产生的随机数也是一样的。
以一个固定的数值作为种子是一个缺点。通常的做法是 :以这样一句srand((unsigned) time(NULL));来取代,这样将使得种子为一个不固定的数,这样产生的随机数就不会每次执行都一样了。详细用法如下:
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
/*Seed the random-number generator with current time
so that the numbers will be different every time we run.*/
srand((unsigned)time(NULL)); /* Display 10 numbers */
for(int i=;i<;i++)
{
cout<<rand()<<endl;
}
return ;
}
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());
/* Display 10 numbers */
for(int i=;i<;i++)
{
cout<<rand()%<<endl;
}
return ;
}






