我用的是rand(),该如何初始化随机种子呢?
程序中有几个地方需要产生随机数,是每次产生随机数都要初始化随机种子,还是整个程序初始化一次就行了?

解决方案 »

  1.   

        在main函数的开头加上这句话就行了:
         srand((unsigned)time(NULL));
        要包含头文件,#include <time.h>
      

  2.   


    每次都调用改变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.
      

  3.   

    用srand函数传递种子,操作系统负责让rand接收种子
      

  4.   

    嗯,本质上是一样的,大家描述有差异而已,俺是在一组rand之前调用一次srand。
      

  5.   

    srand((unsigned)time(NULL)); 这句是粽子种子随便放在哪里,反正做了种子就可以了
      

  6.   

    MSDN里面查一下srand,向下拉一点,下面有个例子。
      

  7.   

    //生成随机种子
    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;
    }
      

  8.   

    定时srand((unsigned)time(NULL))一下,就不会重复了~
      

  9.   

    srand(GetTickCount()); //以windows运行的毫秒数 为轴作种子
    int temp;          
    temp = rand()%11;       //temp的范围0-11
      

  10.   


    如果每次都调用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秒吧?
      

  11.   

    3楼的方法对srand((unsigned)time(NULL)); 这句是粽子 种子随便放在哪里,反正做了种子就可以了
      

  12.   

    赞同15th .
    我就就是出现这个问题才百度,最后自己才发现错误。eg:
    int getrand(int n)
    {
    srand((unsigned)time(NULL));
    return rand()%n;
    }如果主函数
    a=getrand();
    b=getrand();会发现a,b值始终相同,多次运行程序a值可能变化,但是a,b始终相同。(每次调用函数都随机这个种子,调用时间也差不多)所以要将srand()放在函数外,整个程序一次srand即可.