pjm*_*mil 0 c++ arrays random 2d cout
我正在做一些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] << " ";
}
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的输出;
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
我想要实现的是每个组合滚动的次数,例如滚动的次数等等.
你永远不会更新你的count
.
对于你想要运行代码段n次的东西,现在n = 10000,这是你想要的一般方式.
for (int i = 0; i < 10000; ++i)
{
//loop code.
}
Run Code Online (Sandbox Code Playgroud)
另外,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]);
Run Code Online (Sandbox Code Playgroud)
此外,数组索引从零开始,这意味着当你做rand()%6+1
你是从限制值1
来6
并留下了0
一个阵列,这是第一位的位置,所以考虑,而不是仅仅使用
++(nRolls[rand()%6][rand()%6]);
Run Code Online (Sandbox Code Playgroud)
然后,找出你滚动a(i,j)的频率,其中i和j在1到6之间,
cout << "(" << i << "," << j << "):" << nRolls[i-1][j-1] << endl;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1092 次 |
最近记录: |