以下代码每秒输出一个随机数:
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;
这篇关于如何从 rand() 缩小数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!