简单数组无法正常工作

时间:2013-02-16 18:46:16

标签: c++ arrays random

这应该模拟抛出的2个6面骰子,为熟悉结果的数组元素添加+1。例如:a [4]确定滚动了多少4个。出于某种原因,无论它滚动多少次,它都会为数组中的每个元素提供1。即:(a [2] = 1,a [3] = 1,a [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");
}

1 个答案:

答案 0 :(得分:2)

cout << i << " = " << throwDice[i] << endl; 

应该是

cout << i << " = " << a2[i] << endl;

编译代码时应始终使用-Wall,这会立即向您显示错误:

Compilation finished with warnings:
source.cpp: In function 'int main()':
source.cpp:33:38: warning: pointer to a function used in arithmetic 
                           [-Wpointer-arith]

此外,数组索引从0开始,因此为了能够访问a2[12],它必须至少具有13的大小。


最后,system("pause");是一个值得怀疑的想法。我希望cin.get();等待用户按任意键。