我用的是rand(),该如何初始化随机种子呢?
程序中有几个地方需要产生随机数,是每次产生随机数都要初始化随机种子,还是整个程序初始化一次就行了?
程序中有几个地方需要产生随机数,是每次产生随机数都要初始化随机种子,还是整个程序初始化一次就行了?
解决方案 »
- 怎样使列表控件的边框具有凹陷边缘但不带黑线边框?
- xml 中文变?号
- VC绘制图表的问题
- BHO 如何屏蔽网页中的不良信息??
- 《VC++项目开发实践》 《VC++精彩实例详解》 《VC++高级编程》
- 如何做一个多国语言版的程序?
- CButton中的SetCursor()怎么不起作用?
- Mycsdn 1.30(最新版) - 欢迎下载使用!!(可下载CSDN文档)
- 使用MFC Activex ControlWizard向导写ocx遇到问题
- 如何通过程序实现,程序模拟键盘!
- 如何在现有的VC6.0工程中调入 chart 控件---Microsoft Chart Control 请各位师兄师姐指点迷津
- C#调用MFC DLL 接口返回值类型是char * 但内容是乱码
srand((unsigned)time(NULL));
要包含头文件,#include <time.h>
每次都调用改变seed值,随机效果好些The srand function sets the starting point for generating a series of pseudorandom integers. To reinitialize the generator, use 1 as the seed argument. Any other value for seed sets the generator to a random starting point. rand retrieves the pseudorandom numbers that are generated. Calling rand before any call to srand generates the same sequence as calling srand with seed passed as 1.
void ENtool::RandomIni()
{
srand(GetTickCount());
}//生成随机数
int PUGetRandom(int min,int max)
{
// cout<<"new-->temp:"<<endl;
int temp=0;
double count=0;
while(1)
{
count+=rand()%500000;
//生成随机种子
/// srand(GetTickCount()*rand()%(500)+rand()%(1000));
srand(GetTickCount()+count);
temp=rand()%(max+1);
// cout<<"-->temp:"<<temp<<endl;
if(temp>=min && temp<=max)
{
return temp;
}
}
// cout<<"end-->temp:"<<endl;
}
int temp;
temp = rand()%11; //temp的范围0-11
如果每次都调用srand,并且每次都拿time()作种子,再rand,那么这样与直接拿time()作随机结果有什么区别?C库又何必弄两个函数给人调用?另外如果连续取两次随机数:
srand((unsigned)time(NULL));
int rand1 = rand();
srand((unsigned)time(NULL));
int rand2 = rand();
并且程序运行太快话,两次time()返回值相同,直接导致下面rand1、rand2也相同,这样反而做不到“随机效果好些”。如果说每次连续的调用rand前srand一次,那么这些“连续的rand”的整体之间的时间间隔,也未必一定不是0秒吧?
我就就是出现这个问题才百度,最后自己才发现错误。eg:
int getrand(int n)
{
srand((unsigned)time(NULL));
return rand()%n;
}如果主函数
a=getrand();
b=getrand();会发现a,b值始终相同,多次运行程序a值可能变化,但是a,b始终相同。(每次调用函数都随机这个种子,调用时间也差不多)所以要将srand()放在函数外,整个程序一次srand即可.