Random number gererator with in range

I'm trying to build a program to generate a random number with in a range set by two number entered by the user. It's almost working, except sometimes it generates number larger than the range.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  #include <iostream>
#include <ctime> // needed for use of time
#include <cstdlib> // needed for use of rand and srand

int minNum;
int maxNum;
int rNum;

using namespace std;

int main()
{
    // get minimum numbner from user
    cout << "Enter minimum number: " << endl;
    cin >> minNum;

    // get maximum numner from user
    cout << "Enter maximum number: " << endl;
    cin >> maxNum;

    //use time to get seed value for srand
    srand (time (0));

    // generate random number between min and max
    rNum = (minNum) + (rand() % (maxNum));

    // print the random number with in the given range
    cout << "This is a random number between " << minNum;
    cout << " and " << maxNum << ": \n" << rNum << endl;


    return 0;
}
Let's say minNum is 3 and maxNum is 10.

rand() % maxNum will return a number in the range 0 through 9.
Adding minNum, or 3, to each number in that range will make the range 3 through 12 - not 10 as was intended by what was entered for maxNum.

If you really want the largest value in the range to be maxNum, line 25 needs to be tweaked.
line25 rNum = (rand() % (maxNum-minNum+1)+minNum);
Thank you!
Topic archived. No new replies allowed.