-2

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;
}
Abhishek Mhatre
  • 535
  • 2
  • 9
  • 15

4 Answers4

5

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

rdno = rand() % (b-a) + a
Nigloo
  • 76
  • 1
2

Here: rdno = (rand()%50) you assign a pseudo-random number from 0-49. If you add 15, you get numbers from 15 to 64. If you want the numbers from 15 to 50, you can do it for example like this: rdno = (rand()%36) + 15.

EDIT: You need to use %36, as the highest number you want is 50. You can get it, when rand() generates 35, then 35%36 equals 35, and 35+15 equals 50. If you used %35, the highest number you can get is 49.

Honza Dejdar
  • 947
  • 7
  • 19
2

The best way to generate a random number in C that is between [x, y] such that y < 32768 is the following:

int random(int low, int high) {
    return rand() % (high - low + 1) + low;
}

Notice the +1 at the modulus operator, this is to allow inclusion of 50. Without it, your range becomes [15, 50).

Sample run: http://ideone.com/Q6l0e5

For a C++ solution, please look at this: std::unfirom_int_distribution

SenselessCoder
  • 1,139
  • 12
  • 27
1

Because the result of rand() % 50 is added to 15. So your range is 15-65. Your range really is 35 (or 36 if inclusive) so you could change it to:

15 + (rand() % 35)

But really though, if you have access to C++11 use <random>:

#include <random>

std::random_device rd;
std::mt19937 rng(rd());
std::uniform_int_distribution<int> dis(15, 50);

int random_integer = dis(rng);
Community
  • 1
  • 1
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122