2013-02-28 87 views
0

這是應該擲6骰子,並保持多少是唯一的記錄。例如:1 2 3 4 5 6 = 6個唯一編號,1 1 1 1 1 1 = 1個唯一編號,1 2 3 3 3 3 = 3個唯一編號。每擲出一個骰子,我都會得到非常均勻的百分比,大約爲16.7%。爲什麼這些投擲骰子的結果如此平均?

#include <iostream> 
#include <cstdlib> 
#include <ctime> 
using namespace std; 

int numberGenerator() 
{ 
int x = (rand() % 6) + 1; 
return x; 
} 

int diceCounter() 
{ 

int counter[6] = {0,0,0,0,0,0}; 

for (int i = 0; i < 6; i++) 
    { 
    int k = numberGenerator(); 
     if (k == 1) 
      counter[0] = 1; 
     if (k == 2) 
      counter[1] = 1; 
     if (k == 3) 
      counter[2] = 1; 
     if (k == 4) 
      counter[3] = 1; 
     if (k == 5) 
      counter[4] = 1; 
     if (k == 6) 
      counter[5] = 1; 
    } 
return counter[0]+counter[1]+counter[2]+counter[3]+counter[4]+counter[5]; 
}     // returns how many unique numbers were rolled 


int main() 
{ 
srand(time(NULL)); 
cout << diceCounter() << endl; 

int a1 = 0; 
int a2 = 0; 
int a3 = 0; 
int a4 = 0; 
int a5 = 0; 
int a6 = 0; 
int p; 


for (int j = 0; j < 1000000; j++) 
{ 
p = numberGenerator();  // for number of unique numbers, it adds +1 to counter 
if (p == 1) 
a1 += 1; 
if (p == 2) 
a2 += 1; 
if (p == 3) 
a3 += 1; 
if (p == 4) 
a4 += 1; 
if (p == 5) 
a5 += 1; 
if (p == 6) 
a6 += 1; 
} 
cout << "1 ==> " << (a1/1000000.0)*100 << "%" << endl; 
cout << "2 ==> " << (a2/1000000.0)*100 << "%" << endl; 
cout << "3 ==> " << (a3/1000000.0)*100 << "%" << endl; 
cout << "4 ==> " << (a4/1000000.0)*100 << "%" << endl; 
cout << "5 ==> " << (a5/1000000.0)*100 << "%" << endl; 
cout << "6 ==> " << (a6/1000000.0)*100 << "%" << endl; 

       // this results in uniform 16.7% percentages 
} 
+0

大數定律? – WiSaGaN 2013-02-28 01:24:29

+0

但它應該是一個非常低的%爲1或6個唯一的數字,而不是3或4 – Foxic 2013-02-28 01:25:47

回答

3

裏面你的循環,你打電話numberGenerator而非diceCounter

因此,不要計算滾動6個骰子的唯一結果的數量,而是獲得單個滾動的每個數字的計數。正如你所期望的,每個數字都是1/6時間出來的。

+0

非常感謝:) – Foxic 2013-02-28 01:29:27

0

添加到@ MichaelAnderson的回答是:

隨機數都實際上是僞隨機的。

他們的工作值爲seed。所以,在每次調用rand()時間,通話srand()之前補種隨機數生成器: 像這樣:

srand(time(NULL)); 
int r = rand(); 
+0

你只需要在程序開始時做一次,並且只有當你想要每次運行的程序來產生不同的隨機序列。如果你在每個'rand()'調用之前執行它,並且你的循環不到1秒鐘,那麼你每次都會得到相同的隨機數。 – Barmar 2013-02-28 01:47:25

+0

如果你看看main的第一行,它裏面有種子調用('srand') - 這是我尋找的第一個東西...... – 2013-02-28 02:23:52

+0

那麼它不會傷害種子 - 我猜@邁克爾安德森 – 2013-02-28 02:25:31

相關問題