Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random integers c++

I'm trying to produce random integers (uniformly distributed). I found this snippet on an other forum but it works in a very weird way..

 srand(time(NULL));
    AB=rand() % 10+1;

Using this method I get values in a cycle so the value increases with every call until it goes down again. I guess this has something to do with using the time as aninitializer? Something like this comes out.

 1 3 5 6 9 1 4 5 7 8 1 2 4 6 7.

I would however like to get totally random numbers like

1 9 1 3 8 2 1 7 6 7 5...

Thanks for any help


2 Answers

You should call srand() only once per program.

like image 97
Michał Górny Avatar answered Aug 10 '26 10:08

Michał Górny


Also check out the Boost Random Number Library:

Boost Random Number Library

like image 45
ToastedSoul Avatar answered Aug 10 '26 08:08

ToastedSoul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!