random number in a certain range

closed account (4ET0pfjN)
Hi, how do I generate a random number within a range?

Specifically, I want b/t 0 and 20.

I know this much:
#include <cstdlib> //need this to use rand() I think...
#include <ctime> //need this to use time() I think...

using namespace std;

int main()
{
srand( time(0) );
int randNum = rand();
cout<<"Random num:"<<randNum<<endl;

return 0;
}

a%b will give you a number between 0 and b-1 (assuming b>0, a>=0)
Last edited on
Just to add to what ne555 wrote, for the sake of completeness;

The percentage sign (%) is the modulous operator, which returns a remainder after division. So a % b as above will count the number of times b fits into a and return the remainder. As an example 5 % 4 = 1, 2 % 4 = 2, 4 % 4 = 0 and 11 % 4 = 3. The effect of using something like this:

rand() % max_number

where max_number > 0, is basically that you will get an integer less than the value of max_number. Conversely the following will limit your number to a defined range:

rand() % (max_number - min_number) + min_number

where min_number < max_number, but neither need necessarily be larger than 0.

The distribution of the random number will be uniform, meaning that the probability of a given number appearing is exactly 1 / max_number, regardless of the number. You can think of this as a roulette-wheel or dice type of random number.
Last edited on
the formula for the random number generation is
int rand_number = rand() % ( b-a) +a ;
produces the random number between the
 range ( b -a ) to a
For getting a different sequence of pseudo random numbers each time the program is run, you must specify a different seed each time. std::srand() http://cplusplus.com/reference/clibrary/cstdlib/srand/

How can I get random integers in a certain range?

A: The obvious way,
rand() % N /* POOR */
(which tries to return numbers from 0 to N-1) is poor, because the low-order bits of many random number generators are distressingly non-random. (See question 13.18.)

A better method is something like
(int)((double)rand() / ((double)RAND_MAX + 1) * N)
- http://c-faq.com/lib/randrange.html

Also see: http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution

Topic archived. No new replies allowed.