简单数组工作不正常

Simple array not working right

本文关键字:不正常 工作 数组 简单      更新时间:2023-10-16

这应该模拟投掷2个6面骰子,将+1添加到熟悉结果的数组元素中。例如:a[4]表示滚动了多少个4。出于某种原因,无论它滚动多少次,它都会为数组中的每个元素提供1。I.e:(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");
}
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();等待用户按下任何键。