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
}
4

2 回答 2

3

在您的循环中,您正在调用numberGenerator而不是diceCounter.

因此,不是计算滚动 6 个骰子的唯一结果的数量,而是计算单个掷骰的每个数字。正如您所期望的那样,每个数字都有 1/6 的时间出现。

于 2013-02-28T01:27:48.477 回答
0

添加到@MichaelAnderson的答案:

随机数实际上都是伪随机数。

他们致力于seed价值观。因此,每次调用时rand(),请srand()在此之前调用以重新设置随机数生成器的种子:像这样:

srand(time(NULL));
int r = rand();
于 2013-02-28T01:32:31.300 回答