C ++掷骰子分析仪(2D阵列)
c++ dice roll analyser (2D arrays)
我正在做一些 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 274301 245 317 276 292 284 264 260
我试图实现的是每个组合滚动的次数,例如滚动 1、6 的次数等。
你从不更新你的count
。
对于你想要运行代码段n次的东西,现在n = 10000,这是你想要的一般方法。
for (int i = 0; i < 10000; ++i)
{
//loop code.
}
此外,myVariable+=1
始终可以简化为++myVariable
或myVariable++
(如果在分配时不使用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;
}
}
相关文章:
- 库特<<恩德尔;不适用于打印 2D 阵列
- 具有可变尺寸的 C++ 2D 阵列
- 如何遍历 2D 阵列?
- 超级对撞机2D阵列:生成嵌套:包装/尺寸问题
- 动态 2D 阵列.为什么分段错误?
- 尝试使用2D阵列
- 分配给阵列时出现分段错误?黑客排名 2D 阵列 - DS.
- 如何将1D阵列访问为2D阵列
- 分配/访问2d阵列,使得2d子块是连续的
- 重新分配2D阵列并删除旧阵列
- 不使用新的动态2D阵列
- 我正在为2D阵列参数而挣扎
- 特征和巨大的密集 2D 阵列
- 使用 std::transform 在 2d C 阵列上转换为 1d C 数组
- 解除分配此特定 2D 阵列的内存
- 使用两个不同大小的一维阵列制作 2D 阵列
- 返回C 中2D阵列的对角线元素总和
- 2D阵列让我卡住了
- 用pybind11铸造2D阵列
- 我的 2D 阵列无法读取文本文件并正确输出