問(wèn)題描述
生成隨機(jī)數(shù)的最佳方法是什么?
What is the best way to generate random numbers?
推薦答案
當(dāng)且僅當(dāng):
您不是在尋找完美的一致性"或
您沒(méi)有 C++11 支持,甚至沒(méi)有 TR1(因此您別無(wú)選擇)
那么您可能會(huì)考慮使用以下 C 風(fēng)格的解決方案,其中(為了這個(gè)社區(qū)的聲譽(yù)~請(qǐng)參閱 rand() 被認(rèn)為有害) 以刪除線字體書(shū)寫(xiě):
then you might consider using the following C-style solution, which (for the sake of the reputation of this community ~ see rand() Considered Harmful) is written in strike-through font:
這是一個(gè)簡(jiǎn)單的 C 風(fēng)格的函數(shù),它從 min
到 max
的區(qū)間生成隨機(jī)數(shù),包括.這些數(shù)字似乎非常接近均勻分布.
Here's the simple C-style function that generates random number from the interval from min
to max
, inclusive. Those numbers seem to be very close to being uniformly distributed.
int irand(int min, int max) {
return ((double)rand() / ((double)RAND_MAX + 1.0)) * (max - min + 1) + min;
}
并且在使用之前不要忘記調(diào)用srand
:
int occurences[8] = {0};
srand(time(0));
for (int i = 0; i < 100000; ++i)
++occurences[irand(1,7)];
for (int i = 1; i <= 7; ++i)
printf("%d ", occurences[i]);
輸出:14253 14481 14210 14029 14289 14503 14235
還可以看看:
生成范圍內(nèi)的隨機(jī)數(shù)?
在整個(gè)范圍內(nèi)均勻生成隨機(jī)數(shù)
找些時(shí)間,至少觀看上述 視頻的前 11 分鐘一個(gè)>
使用
只是就像 Kerrek SB 已經(jīng)指出的那樣.
use <random>
just like it was pointed out by Kerrek SB already.
這篇關(guān)于在 C++ 中生成隨機(jī)數(shù)的最佳方法是什么?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!