开发者

How I can generate different random numbers in one moment in c++?

开发者 https://www.devze.com 2023-02-21 12:01 出处:网络
How I can generate different random numbers in one moment in c++? N开发者_运维知识库ow I use while ( flag )

How I can generate different random numbers in one moment in c++?

N开发者_运维知识库ow I use

while ( flag )
{
   ....
   srand( time( NULL) ); 
   int rndSig = rand() % 10 + 1;
   ......
}

But at one moment all numbers are equal. How I can generate different numbers in while loop?


Move the srand outside of the while loop. You only need to call it once, rand() keeps static state.


You don't seed the random generator directly before you use it. Just use srand once before the loop.


Like this :

srand( time( NULL) ); 
while ( flag )
{
   ....
   int rndSig = rand() % 10 + 1;
   ......
}

If you need different distribution, or better randomness, you need to use a library.

0

精彩评论

暂无评论...
验证码 换一张
取 消