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.
#include <iostream>
#include <ctime> // needed for use of time
#include <cstdlib> // needed for use of rand and srand
int minNum;
int maxNum;
int rNum;
usingnamespace 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;
}
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.