在测试随机数生成时:
方法一)我是这样完成产生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()函数中,每次取的种子是不一样啊!所以随机数也应该不一样!
大家帮忙看看方法二错在哪里,怎么解决!
方法一)我是这样完成产生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()函数中,每次取的种子是不一样啊!所以随机数也应该不一样!
大家帮忙看看方法二错在哪里,怎么解决!
放在while循环外
srand()本生散步随机粒子的,GetTickCount()的值你每次都一样(因为运算速度太快,最小单位太大)。因此导致都是同一个值。等于说你固定了随机粒子分布。所以rand()函数都一样。可以尝试3,4楼的方法。
{
static bool ini=false;
if(ini==false){
srand(GetTickCount());
ini=true;
}
int r=rand()%iMax;
return r;
}
只用一次,最好在主函数里调用。