Hello I got a problem while trying to use rand() fucntion.
Just by using it its self it generates a random number from 0 to RAND_MAX. The prob is that I don't know rand max, so how can I make
a costume generation, like generating from 0 20 or 0 to 30.
Thx in advance.

Recommended Answers

All 2 Replies

x = rand() % 30 for 0-29

To create random numbers within a limited range you need to take the modulo (% operator) of the random number and the size of your range. You then need to add the minimum allowable value to the result.

i.e. to produce numbers in the range [20, 45):

const int myMin = 20
const int myMax = 45;
int myRange = myMax-myMin; //myRange = 25
int myRand = (rand() % myRange) + myMin;

[edit]
phooey, Walt beat me to it :P

[edit2]
It should be noted that this will never generate the max value of the range. If you need to generate [20, 45], you will have to compensate by adding 1 to your myMax value (i.e. const int myMax = 46; ).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.