user2468338 user2468338 - 1 day ago 4
C++ Question

Generation of random number(within a limit) code overshooting the upper limit

My Computer science C++ book says that to generate random numbers with a lower limit (in this case, 15)and upper limit(in this case, 50), we have to use the following code. But when I used it I got the output as 56,32,49,15. Is there a reason why the program is giving results that overshoot the upper limit or is the code wrong.

#include <iostream>
#include <stdlib.h>

using namespace std;
int main(){
int i,rdno;
for(i=1;i<5;++i){
rdno=(rand()%50)+15;
cout <<rdno<<endl;
}
return 0;
}

Answer

If you want to generate a number in [a;b) use

rdno = rand() % (b-a) + a
Comments