gpt4 book ai didi

c++ - modulus 和 rand() 如何工作?

转载 作者:太空狗 更新时间:2023-10-29 23:23:16 26 4
gpt4 key购买 nike

所以,我对此很着迷。

rand() % 6 将始终产生 0-5 之间的结果。

但是,当我需要介于 6 到 12 之间时。

我应该有 rand() % 6 + 6

0+6 = 6.
1+6 = 7.
...
5+6 = 11. ???

如果我想要间隔 6-12,是否需要 + 7?但是,0+7=7。它什么时候会随机化 6?

我在这里错过了什么?哪一个是获得 6 到 12 之间的随机数的正确方法?为什么?好像我在这里遗漏了什么。

最佳答案

如果 C++11 是一个选项,那么您应该使用 random headeruniform_int_distrubution .正如 James 在评论中指出的那样,使用 rand% 存在很多问题,包括分布偏差:

#include <iostream>
#include <random>

int main()
{
std::random_device rd;

std::mt19937 e2(rd());

std::uniform_int_distribution<int> dist(6, 12);

for (int n = 0; n < 10; ++n) {
std::cout << dist(e2) << ", " ;
}
std::cout << std::endl ;
}

如果你必须使用 rand那么应该这样做:

rand() % 7 + 6

更新

使用 rand 的更好方法如下:

6 + rand() / (RAND_MAX / (12 - 6 + 1) + 1)

我从C FAQ 中获得了它,并对其进行了解释 How can I get random integers in a certain range?问题。

更新 2

Boost也是一个选项:

#include <iostream>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>

int main()
{
boost::random::mt19937 gen;
boost::random::uniform_int_distribution<> dist(6, 12);

for (int n = 0; n < 10; ++n) {
std::cout << dist(gen) << ", ";
}
std::cout << std::endl ;
}

关于c++ - modulus 和 rand() 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19553265/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com