2013-02-28 86 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