How do I scale down numbers from rand()?

Maxpm picture Maxpm · Nov 16, 2010 · Viewed 20.1k times · Source

The following code outputs a random number each second:

int main ()
{
    srand(time(NULL)); // Seeds number generator with execution time.

    while (true)
    {
        int rawRand = rand();

        std::cout << rawRand << std::endl;

        sleep(1);
    }
}

How might I size these numbers down so they're always in the range of 0-100?

Answer

Blastfurnace picture Blastfurnace · Nov 16, 2010

If you are using C++ and are concerned about good distribution you can use TR1 C++11 <random>.

#include <random>

std::random_device rseed;
std::mt19937 rgen(rseed()); // mersenne_twister
std::uniform_int_distribution<int> idist(0,100); // [0,100]

std::cout << idist(rgen) << std::endl;