我需要这段代码来生成一个介于 5 和 8 之间的数字,然后将其分配给一个变量。然而,当我让它只给我一个数字而不是多个时,它只给我相同的数字。当我将它设置为给 e 倍数时,它会给我随机数。
#include <random>
#include <iostream>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(5, 8);
for (int n=0; n<1; ++n)
std::cout << dis(gen) << ' ';
std::cout << '\n';
}
最佳答案
1 - 你“只有一个数字”:
因为您的 for 循环只进行一次迭代。
for (int n=0; n<1; ++n)
^
Here
2 - 如果您总是看到相同的伪随机序列,这是因为种子本身就是伪随机的:对于 std::random_device
,这是 implementation specific :
Note that std::random_device may be implemented in terms of a pseudo-random number engine if a non-deterministic source (e.g. a hardware device) is not available to the implementation.
请注意,您在 ideone 上的示例不是伪随机的并且工作正常:http://ideone.com/lysKrt
作为 rd
的替代方案,您可以使用系统时间作为种子:
#include <chrono>
// ...
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::mt19937 gen(seed);
关于c++ - 我正在尝试在 C++ 中制作一个介于 5 和 8 之间的随机数生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24052421/