这应该是模拟2个6面骰子被抛出,将+1添加到熟悉结果的数组的元素。例如:a [4]表示有多少个4滚动。出于某种原因,无论滚动多少次,它都会为阵列中的每个元素提供1。即:(1 [2] = 1,A [3] = 1,[4] = 1等)简单阵列不能正常工作
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
int throwDice() // generates random number ranging 2-12
{
int x = (rand() % 6) + 1;
int p = (rand() % 6) + 1;
return x + p;
}
int main()
{
srand (time(NULL));
int y;
cout << "Roll dice how many times?" << endl;
cin >> y;
int a2[12]; // initializes and declares elements a[2] - a[12] with value 0
for (int i = 2; i <= 12; i++)
a2[i] = 0;
for (int i = 0; i <= y; i++) // runs random number generator, adds +1 to that element
{
a2[throwDice()]++;
}
for (int i = 2; i <= 12; i++) // prints how many results per element
cout << i << " = " << throwDice[i] << endl;
system("pause");
}
你搞砸了你的指数。没有'a2 [12]' - 'a2'中的最后一个对象是'a2 [11]'。 – 2013-02-16 18:48:28
而不是使用数组,我建议你看看例如['的std :: unordered_map'](http://en.cppreference.com/w/cpp/container/unordered_map)。 – 2013-02-16 18:49:56
@JoachimPileborg - 这似乎是一个数组的完美案例(一旦索引得到整理)。为什么要添加无序映射的开销? – 2013-02-16 19:13:08