SFML community forums

Help => General => Topic started by: Lolq on November 07, 2014, 03:34:52 am

Title: Random number
Post by: Lolq on November 07, 2014, 03:34:52 am
Hey guys :)
I need a little help with my random number generation for drop function.
So, here is the way i wrote it:

(click to show/hide)

and here is rand:
(click to show/hide)

The problem is that when enemy1 and enemy2 are killed at almost the same time they alway both drop item, any idea why it's like this or maybe any other way to get random number? or maybe it's just a really really really big coincidence every time? ;d
Title: Re: Random number
Post by: Jesper Juhl on November 07, 2014, 03:55:42 am
First of all, don't use rand() (http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful). Use what's provided in the random (http://en.cppreference.com/w/cpp/numeric/random) header.

Why do you seed with srand() before every call to rand()? Seed the generator just once. The way you did it, every two calls to random_drop within the same second will use the same seed and thus generate the same number.
And why on earth is that variable volatile? 

Edit: see also this (http://en.sfml-dev.org/forums/index.php?topic=16179.msg115789#msg115789) post (hint: searching the forum can be useful  ;) ).
Title: Re: Random number
Post by: FRex on November 07, 2014, 07:43:12 am
Don't call srand more than once in your program.
Title: Re: Random number
Post by: Lolq on November 07, 2014, 12:22:37 pm
Thanks for these answers :)
And the volatile was there just because i was trying all the pointless things that i knew won't work ;p