Jump to content
  • Advertisement
Sign in to follow this  
simon_brown75

integer rounding and rand() in c++

This topic is 2304 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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-

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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!