Sign in to follow this  
super_llama

rand() function

Recommended Posts

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

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