• Advertisement
Sign in to follow this  

rand() function

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

I'm trying to use the rand() function (C language) to randomly pick a number between 1 and 5. How do I go about doing that?

Share this post


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