user2468338 user2468338 - 9 months ago 51
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;
cout <<rdno<<endl;
return 0;

Answer Source

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

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