# rand() function

## 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 on other sites
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 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);}

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628301
• Total Posts
2981913

• 10
• 11
• 11
• 10
• 10