如何从 rand() 缩小数字?

2021-12-21 00:00:00 generator random c++ mersenne-twister

以下代码每秒输出一个随机数:

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);
    }
}

如何缩小这些数字的大小,使其始终在 0-100 的范围内?

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

推荐答案

如果您使用的是 C++ 并且关心良好的分布,您可以使用 TR1 C++11 .

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;

相关文章