Sign in to follow this  
simon_brown75

integer rounding and rand() in c++

Recommended Posts

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-

[code]int ExplosionType = rand () / ( RAND_MAX / 3 );[/code]

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.

Share this post


Link to post
Share on other sites
[s]Correct[/s] [size=2](Confused "rounding down" with "truncation").[/size] 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

Share this post


Link to post
Share on other sites
I suggest reading some of this thread, particularly post #9:
[url="http://www.gamedev.net/topic/620530-getting-random-numbers-into-a-variable/"]http://www.gamedev.net/topic/620530-getting-random-numbers-into-a-variable/[/url]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this