# Question about the rand() function

• 03-26-2007
V4D3R
Question about the rand() function
I'm trying to make a program that will prompt a user to enter a starting value and an ending value. When that is done, I will take those values and call a function that will create a 100 random numbers for me within those two input values.

Here is the code:

Code:

```#include <iostream> #include <cstdlib> #include <time.h> using namespace std; void main() {         srand (unsigned int(NULL));         int nRandomNumber = 0;         int nStartingValue, nEndingValue;         cout << "Enter a starting value: ";         cin >> nStartingValue;         cout << endl;         cout << "Enter an ending value: ";         cin >> nEndingValue;         cout << endl;                 for (int j = 0; j < 100; j++)         {                 nRandomNumber = rand() % (nEndingValue + 1) + nStartingValue;                 cout << nRandomNumber << " ";         } }```
I started the program in a main() function to see if the random numbers do come but they are always out of range. Any help would be great.
• 03-26-2007
Daved
The mod part of the equation reduces the possible values to between 0 and one less than whatever you mod with. In your case, that means that you are making the possible values fall between 0 and nEndingValue. Then your code adds nStartingValue to it to make the range (0 + nStartingValue) to (nEndingValue + nStartingValue). Obviously, this is not what you want.

In the case of actual numbers, if the starting value is 5 and the ending value is 20, then after the mod part you get numbers from 0-20, and after the addition you get 5-25. You want 5-20, so the problem is the mod part is not reducing the possible values enough. See if you can figure out how to change that part of the equation to get the right value.

Or you can search for the proper equation, which is used a lot and should not be hard to find.
• 03-26-2007
V4D3R
thanks for your help

sorry im a newb i dunno what mod means :P
• 03-26-2007
Daved
The &#37; part of the equation is the mod. It means find the remainder. So 20 % 3 is 2 and 10 % 5 is 0.

A random number % 20 will always be somewhere between 0 and 19, which is why it is used in this equation to fit the possible values into a range.
• 03-26-2007
V4D3R
gotcha :D

thanks again
• 03-26-2007
V4D3R
Code:

`nRandomNumber = rand() &#37; ((nEndingValue - nStartingValue)+ 1) + nStartingValue;`
I got this. It works great now. Thanks :D

P.S. I love this board. :)