int main()
{
srand((unsigned)time(0));
int random_integer;
int lowest=0, highest=10;
int range=(highest-lowest)+1;
for(int index=0; index<20; index++){
random_integer = (rand() % range) + lowest/(RAND_MAX + 1.0);
cout << random_integer << endl;
}
}
I am getting the output from 0 to 10, 11 numbers, but I don’t want to get number 10, just numbers 0 to 9, that means 10 random numbers, what should I do?
Modulo operation
x % c;returns the remainder of division of numberxbyc. If you dox % 10then there are10possible return values:0 1 2 3 4 5 6 7 8 9.Note that generating random numbers by using
rand()with%produces skewed results and those numbers are not uniformly distributed.Here’s the simple C-style function that generates random number from the interval from
mintomax, inclusive:Note, that numbers generated by this functions are uniformly distributed:
output:
14253 14481 14210 14029 14289 14503 14235Also have a look at:
Generate a random number within range?
Generate random numbers uniformly over an entire range
What is the best way to generate random numbers in C++?