bluthunder bluthunder - 1 year ago 147
C++ Question

How to generate random numbers between 2 values, inclusive?

I need help figuring out how to generate a set amount of random numbers between two user-inputted values, inclusively. Just so you know, I have searched for this but am not finding what I have just stated. Here is my code:

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main()
int userBeg, userEnd, outPut;

cout << "Enter a start value: ";
cin >> userBeg;
cout << "Enter an end value: ";
cin >> userEnd;

srand(time(NULL)); //generates random seed val

for (int i = 0; i < 5; i++) {
//prints number between user input, inclusive
outPut = rand()%((userEnd - userBeg) + 1);
cout << outPut << " ";
}//end for

return 0;
}//end main

I'm confused with the output I get for the following ranges:
1-100 yield output numbers which fall in-between, but not including, the boundaries such as 50, 97, 24, 59, 22.
But, 10-20 yield numbers such as 1, 14, 6, 12, 13. Here, the output is outside of the boundaries as well as in-between them. What am I doing wrong?

Thank you in advance for your help!

Answer Source

rand returns number between 0 and RAND_MAX. By taking modulo userEnd - userBeg + 1 the boundaries will be limited to 0 and userEnd - userBeg. If the random number should be within given boundaries, then userBeg should be added, so the calculus becomes

    outPut = rand()%((userEnd - userBeg) + 1) + userBeg; 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download