在测试随机数生成时:
方法一)我是这样完成产生N个随机数,然后显示在屏幕。void CSrandDlg::OnButton1() 
{
// TODO: Add your control notification handler code here
int r;
CString str,str1;
srand(GetTickCount());
for(int i=0;i<=10;i++)
{
r=rand()%20;
    str.Format("数:%d,",r);
str1=str1+str;
}
CDC *dc=GetDC();
dc->TextOut(10,10,str1);
dc->DeleteDC();
}

上面这段代码能在屏幕上输出10个不同的随机数。为了提高程序可读性,我单独写了一个随机数成生函数如下:
方法二)int CSrandDlg::Random(int iMax)
{
srand(GetTickCount());
int r=rand()%iMax;
return r;
}

然后再调用它生成随机数:

void CSrandDlg::OnButton2() 
{
// TODO: Add your control notification handler code here
int times=0; CString str,str1;
while(times<=10)
{
times++;
str.Format("数%d:%d     ",times,Random(20));
str1+=str;
}
CDC *dc=GetDC();
dc->TextOut(10,10,str1);
dc->DeleteDC();
}

上面代码每次在屏幕上输出的10随机数都是一样的。不知道为什么,按理说,在Random()函数中,每次取的种子是不一样啊!所以随机数也应该不一样!
大家帮忙看看方法二错在哪里,怎么解决!

解决方案 »

  1.   

    我认为你最好的处理办法就是只设一次种子,然后调若干次 rand,而不是每调一次就设一次种子
      

  2.   

    srand(GetTickCount());放在while循环外
      

  3.   

    srand(time(0)); //保证每次运行产生的随机数都不一样
    放在while循环外
      

  4.   

    我认为:
    srand()本生散步随机粒子的,GetTickCount()的值你每次都一样(因为运算速度太快,最小单位太大)。因此导致都是同一个值。等于说你固定了随机粒子分布。所以rand()函数都一样。可以尝试3,4楼的方法。
      

  5.   

    不错就都是srand(GetTickCount())有问题,用srand(time(0))就可以啦,上面的老兄回答的很不错。
      

  6.   

    time(0)当然用过,结果还是一样!
      

  7.   

    int CSrandDlg::Random(int iMax)
    {
      static bool ini=false;
      if(ini==false){
       srand(GetTickCount());
       ini=true;  
      }
      int r=rand()%iMax;
      return r;
    }
      

  8.   

    srand((int)time(NULL));
    只用一次,最好在主函数里调用。