<分区>
我在 C++11 中生成随机数。当我运行我的代码时
using namespace std;
static std::mt19937_64 rng;
int main() {
rng.seed(11);
std::cout << rng() << std::endl;
}
它返回随机数。但是,我想将其限制在一个数字范围内,比如 1-1000。我该怎么做,使用新的 <random>
C++11 中引入的文件/库?
<分区>
我在 C++11 中生成随机数。当我运行我的代码时
using namespace std;
static std::mt19937_64 rng;
int main() {
rng.seed(11);
std::cout << rng() << std::endl;
}
它返回随机数。但是,我想将其限制在一个数字范围内,比如 1-1000。我该怎么做,使用新的 <random>
C++11 中引入的文件/库?
最佳答案
使用 std::uniform_int_distribution
来自 <random>
.
例子:
#include <random>
#include <iostream>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int> dis(1, 1000);
std::cout << dis(gen) << '\n';
}
<random>
header 包含许多您可以使用的其他发行版。你可以看看here
关于c++ - 使用 <random> 将随机数生成限制在一个范围内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17663901/