Jump to content
  • Advertisement
Sign in to follow this  
super_llama

rand() function

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

Advertisement
to cap a random number you need to use mod (x % y)... basically it returns the remainder when x is divided by y, which ensures that the it will always return a number between 0 and (y-1). You don't really need to know that though, the important thing is that when you mod something, you get a number 1 less than the mod value.

int a = rand() % 5;

that will return a number between (and including) 0 to 4. If you want 1 to 5 then just add one to that:

int a = (rand() % 5) + 1;

(although c always starts its count from 0 so mostly you want 0-4 instead of 1-5, especially for array indexs)

Share this post


Link to post
Share on other sites
i find sumin like this works:

i hope i remembered it right, some one can correct me if wrong or better way about it.



float random_number(float lowest, float highest)
{
if( lowest > highest){ swap(highest, lowest); };

float range = highest - lowest;

return lowest + (range * rand()/RAND_MAX);
}



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!