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.

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);}

1. 1
Rutin
26
2. 2
3. 3
4. 4
5. 5

• 9
• 11
• 10
• 13
• 20
• Forum Statistics

• Total Topics
632948
• Total Posts
3009389
• Who's Online (See full list)

There are no registered users currently online

×