C++ 随机数不随机怎么回事儿

谨记srand()不要调用两次或两次以上。

void main() 
{ 
for(int i=0;i<10;i++) 
{ 
srand( (unsigned)time( NULL ) ); 
cout<<rand()<<endl; 
} 
}

这样调用的时候,因为CPU高速的关系,调用的srand( (unsigned)time( NULL ) );生成的种子数一样。导致rand()产生的随机数也一样。
改为:

void main() 
{ srand( (unsigned)time( NULL ) );
for(int i=0;i<10;i++) 
{
cout<<rand()<<endl; 
} 
}

有时候这些错误很隐蔽,在构造函数中做了一个check方法。在check方法中调用init方法,然后在init方法中产生随机数。注意如果srand( (unsigned)time( NULL ) );被写进了check()或者init()等方法中,一定要保证该方法在构造的时候只被调用一次。最好是把该行代码srand( (unsigned)time( NULL ) );写到构造函数中进行初始化种子的操作。

参考:[https://blog.csdn.net/iteye_18051/article/details/81466455]

猜你喜欢

转载自blog.csdn.net/weixin_41168674/article/details/82773870
今日推荐