Jump to content
  • Advertisement
Sign in to follow this  
rexTroianus

Random numbers

This topic is 4837 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

Hello, I know I saw this somewhere, but I can't remember where. How to randomize a number in C++ in range from 1 to 6 ? Thank you, RexTroianus

Share this post


Link to post
Share on other sites
Advertisement
Heres a general function to do what you wish:

void random(int min, int max)
{
return rand() % (max - min) + min;
}


You could add checks for division by zero and negative numbers if you wanted too. Also, in the above code, 6 wont be included in the range generated if random(1,6) is called.

arm.

Share this post


Link to post
Share on other sites

#include <cstdlib>

int randomNumber(int min, int max) {
return rand() % (max-min+1) + min;
}


The % operator gives you the remainder from an integer divide, and rand() gives you a random number from 0 to RAND_MAX. By combining them you can get a random number within a limit. If you want this explaining better let me know. I know it wasn't very clear.

Share this post


Link to post
Share on other sites
Quote:
Original post by rexTroianus
Anyway, why it always generates same numbers when I start the application?


Have you called srand()?
You need to call srand to set the seed for the rand() random number generator.

The most common way is probably:
srand( time(NULL) );

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!