integer rounding and rand() in c++

Started by
3 comments, last by iMalc 12 years ago
Hi, just a quick question.

Am I right in thinking that rounding is always done down in integer math in C++, and therefore the following line-

int ExplosionType = rand () / ( RAND_MAX / 3 );

would give equal occurances of 0, 1 and 2 with a very rare (1 in 32767) chance of a 3.

(Compiler is VC++ 2010 Express if that's important)

Thanks,
Simon.
Advertisement
[s]Correct[/s] [size=2](Confused "rounding down" with "truncation"). As TheUnbeliever points out, the decimal is truncated. However, you can try these other solutions which avoid the possibilitiy of obtaining a 3:

rand() / ( RAND_MAX / 3 + 1 );
rand() % 3
(rand() >> 4) % 3
Thank you, that explains some very rare oddness in my game, and how to fix it.

Cheers.
rounding is always done down


Nearly: towards zero.
[TheUnbeliever]
I suggest reading some of this thread, particularly post #9:
http://www.gamedev.net/topic/620530-getting-random-numbers-into-a-variable/
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

This topic is closed to new replies.

Advertisement