我在试着用随机库。我知道这里有一个类似的问题:分布包容范围。据我所读,应该是[0,10]。我试着得到0,10,但我尝试过这个解决方案,但它对我不起作用。我搞不懂为什么。这里有一些代码。
std::vector<int> vec;
int main()
{
const int min = 0;
const int max = 10;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(min, std::nextafter(max, INT_MAX));
const int MAX = 10;
for (int i = 0; i < MAX; i++)
{
int t = dis(gen);
vec.push_back(t);
}
for (auto& i : vec)
std::cout << i << std::endl;
system("pause");
return 0;
}我试过:
std::uniform_real_distribution<> dis(min, std::nextafter(max, INT_MAX));
std::uniform_real_distribution<> dis{ 0, 10 };
std::uniform_real_distribution<> dis(min, max);它只产生0到9作为随机,不包括10,我希望它。我在做VS2013。
发布于 2015-09-09 19:34:18
分布工作在实数,而不是整数。因此,当dis(gen);存储在Integer int t中时,它的实际结果很可能会被截断。因为在Real域中有无限多的可能值,所以不太可能在十次尝试中准确返回10.0,即使返回了,浮点不精确也可能将其转换为9.999999或类似的值。
如果打开编译器的警告,这将显示为浮动到int精度丢失警告。
快速解决方案是
https://stackoverflow.com/questions/32487493
复制相似问题