To get an even distribution, you must first divide RAND_MAX
static_cast<int>(21*static_cast<double>(rand())/(RAND_MAX+1)) - 10
using
rand() % 21 - 10;
faster and often used in applications, but the given distribution is not homogeneous. The function rand()generates numbers from 0to RAND_MAX. If RAND_MAX%21!=0lower numbers are more likely to be generated.
You can also use the modulo method, but with some random numbers discarded:
int randMax = RAND_MAX - RAND_MAX%21;
int p=RAND_MAX+1;
while(p>randMax)
p=rand();
x=p%21 - 10;
Edit (comments from Johannes and Steve):
RAND_MAX , , - , .
Boost Random Library ( Danvil), .