Original Post
Im currently trying to build a random number generator for my game, and before I did it, I read a little about rand(). One of the first things I found out was that I need to call srand() with time(null) in order to pass a seed to rand(), so it doesnt return always the same order of values. After reading this, I tried to build my random number generator, but there seems to be an important point I missed, and so I wanted to ask you people here whats going wrong. My idea was to call srand() right in the main method of my game (actually as the first thing I do at all) and then have a generate_random_number(int lowerbound, int upper_bound) function in my FrameWork class. The strange thing is now, that if I call rand() in my main.cpp right after calling srand(), it returns numbers, but rather simply increasing ones, not randomly small or big.. If I call rand() now in my function in the framework class, it simply returns always the same order of random numbers, just like I never called srand(). I already searched my code for other occurences of srand(), but there are none. Code in main.cpp: output: output:
#include <string>
#include <cstdlib>
#include <cstdio>
#include <ctime>
int main (int argc, char *argv[])
{
std::cout << "[Main]time is: " << (unsigned int) time(NULL) << std::endl;
printf ("First number: %d\n", rand() );
printf ("Second number: %d\n", rand());
srand((unsigned int) (time(NULL)));
printf ("random number: %d\n", rand());
}
Quote:Code in framework.cpp:
[Main]time is: 1206836264 First number: 41 Second number: 18467 random number: 12108 //this is maybe 12132 the next time I run my game
Uint32 Framework::random_generator(Uint32 lower_bound, Uint32 upper_bound)
{
unsigned int random_number = (unsigned int) std::rand();
printf ("[FrameWork]random number: %d\n", random_number);
Uint32 dest_range = upper_bound - lower_bound;
Uint32 return_value = Uint32 (lower_bound + ((Uint32) random_number % dest_range));
}
Quote:Notice that 41 and 18467 are the first numbers rand() returns without seed or seed 1... And I shortened the code and the output, so dont try to correct syntax errors, pls.
[FrameWork]random number: 41 [FrameWork]random number: 18467