C ++掷骰子分析仪(2D阵列)

c++ dice roll analyser (2D arrays)

本文关键字:2D 阵列 分析仪 掷骰子      更新时间:2023-10-16

我正在做一些 c++ 练习,并尝试编写一个程序来计算 10000 次尝试后掷骰子组合的次数。我使用了一个 2D 数组来存储每个可能的骰子组合,我执行 10000 rand()%6+1并递增它随机分配的内存中的值。

这是我的尝试。

cout << "nDice roll analyser" << endl;
const int first = 6;
const int second = 6;
int nRolls[first][second];
int count = 0;
while (count < 10000){
    nRolls[rand()%6+1][rand()%6+1]+=1;
    count++;
}
for (int i=0;i<first;i++){
    for (int j=0;j<second;j++){
        cout << nRolls[i][j] << " ";
    }
}

这是我得到的输出;

0 0 0 0 0 0 0 269 303 265 270 264 228 289 272 294 290 269 262 294 303 277 265 294 288 266 313 274

301 245 317 276 292 284 264 260

我试图实现的是每个组合滚动的次数,例如滚动 1、6 的次数等。

你从不更新你的count

对于你想要运行代码段n次的东西,现在n = 10000,这是你想要的一般方法。

for (int i = 0; i < 10000; ++i)
{
    //loop code.
}

此外,myVariable+=1始终可以简化为++myVariablemyVariable++(如果在分配时不使用myVariable的值,则最好使用第一个。有关前/后增量的更多信息,请参阅:http://gd.tuwien.ac.at/languages/c/programming-bbrown/c_015.htm

所以而不是nRolls[rand()%6+1][rand()%6+1]+=1;你可以改为做

++(nRolls[rand()%6+1][rand()%6+1]);

此外,数组是零索引的,这意味着当您执行rand()%6+1时,您将值从 1 限制为 6,并省略数组的0位置,这是第一个,因此请考虑仅使用

++(nRolls[rand()%6][rand()%6]);

然后,要找出你掷出 a (i,j) 的频率,其中 i 和 j 介于 1 和 6 之间,

cout << "(" << i << "," << j << "):" << nRolls[i-1][j-1] << endl;

您将在这里遇到问题,因为您要将 +1 添加到 rand()%6 您永远不会增加任何索引为零的元素的计数。允许递增的最小元素索引从 1 开始。

好的,谢谢你的帮助。这是正确显示的更新代码!

cout << "nDice roll analyzer" << endl;
srand(time(0));
const int first = 6;
const int second = 6;
int nRolls[first][second];
int count = 0;
while (count < 10000){
    nRolls[rand()%6][rand()%6]++;
    count++;
}
for (int i=0;i<first;i++){
    for (int j=0;j<second;j++){
        cout << "(" << i+1 << "," << j+1 << ")" << nRolls[i][j] << endl;
    }
}