Hello!
I am taking a course on programming, and we're using C++. We had an assignment where, at some point, we needed to code a function that would return a random number in an [upper, lower] interval. I used the following:
lower + (int) (upper * (rand() / (RAND_MAX + 1.0)));
I did not forget to change srand
by using srand((unsigned int) time(0))
.
However, I get the same value every time! I asked my professor for help and he, after some investigation, found out that the first number generated by rand()
isn't that random... The higher order bits remained unchanged, and since this implementation uses them, the end result isn't quite what I expected.
Is there a more elegant, yet simple solution than to discard the first value or use remainders to achieve what I want?
Thanks a lot for your attention!
~Francisco
EDIT: Thank you all for your input. I had no idea rand()
was such a sucky RNG :P