問題描述
所以,我一直對這個很著迷.
So, I've been nuts on this.
rand() % 6 將始終產生 0-5 之間的結果.
rand() % 6 will always produce a result between 0-5.
但是,當我需要介于兩者之間時,可以說是 6-12.
However when I need between, let's say 6-12.
我應該有 rand() % 6 + 6
Should I have rand() % 6 + 6
0+6 = 6.
1+6 = 7.
...
5+6 = 11. ???
如果我想要間隔 6-12,那么我需要 +7 嗎?但是,0+7 = 7.什么時候會隨機6個?
So do I need to + 7 If I want the interval 6-12? But then, 0+7 =7. When will it randomize 6?
我在這里錯過了什么?哪個是在 6 到 12 之間隨機數的正確方法?為什么?我好像在這里遺漏了什么.
What am I missing here? Which one is the correct way to have a randomized number between 6 and 12? And why? It seems like I am missing something here.
推薦答案
如果 C++11 是一個選項,那么您應該使用 隨機標頭 和 uniform_int_distrubution.正如 James 在評論中指出的那樣,使用 rand 和 %
有很多問題,包括偏差分布:
If C++11 is an option then you should use the random header and uniform_int_distrubution. As James pointed out in the comments using rand and %
has a lot of issues including a biased distribution:
#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 那么應該這樣做:
if you have to use rand then this should do:
rand() % 7 + 6
更新
使用 rand
的更好方法如下:
A better method using rand
would be as follows:
6 + rand() / (RAND_MAX / (12 - 6 + 1) + 1)
我從 C 常見問題解答 中獲得了這個,并解釋了 如何我得到一定范圍內的隨機整數? 問題.
I obtained this from the C FAQ and it is explained How can I get random integers in a certain range? question.
更新 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 ;
}
這篇關于模數和 rand() 如何工作?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!