0

这应该模拟投掷 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");
}
4

1 回答 1

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();等待用户按任意键。

于 2013-02-16T18:47:39.660 回答