所以,我一直很疯狂.
rand()%6将始终产生0-5之间的结果.
但是当我需要时,请说6-12.
我应该有rand()%6 + 6
0+6 = 6.
1+6 = 7.
...
5+6 = 11. ???
Run Code Online (Sandbox Code Playgroud)
所以我需要+ 7如果我想要6-12的间隔?但是,0 + 7 = 7.什么时候会随机化6?
我在这里错过了什么?哪一个是6到12之间随机数的正确方法?为什么?好像我在这里遗漏了一些东西.
Sha*_*our 10
如果C++ 11是一个选项,那么你应该使用random header和uniform_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 ;
}
Run Code Online (Sandbox Code Playgroud)
如果你必须使用rand那么这应该做:
rand() % 7 + 6
Run Code Online (Sandbox Code Playgroud)
更新
使用的更好方法rand如下:
6 + rand() / (RAND_MAX / (12 - 6 + 1) + 1)
Run Code Online (Sandbox Code Playgroud)
我从C FAQ中获得了这个,并解释了如何在一定范围内获得随机整数?题.
更新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 ;
}
Run Code Online (Sandbox Code Playgroud)