2013-02-16 145 views
0

这应该是模拟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"); 
} 
+0

你搞砸了你的指数。没有'a2 [12]' - 'a2'中的最后一个对象是'a2 [11]'。 – 2013-02-16 18:48:28

+0

而不是使用数组,我建议你看看例如['的std :: unordered_map'](http://en.cppreference.com/w/cpp/container/unordered_map)。 – 2013-02-16 18:49:56

+0

@JoachimPileborg - 这似乎是一个数组的完美案例(一旦索引得到整理)。为什么要添加无序映射的开销? – 2013-02-16 19:13:08

回答

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

+0

新问题,现在它只运行一次。因此,如果我滚动2321次,所有内容= 0,除了1个数字= 1。 – Foxic 2013-02-16 18:49:12

+2

'int a2 [12]; for(int i = 2; i <= 12; i ++)a2 [i] = 0;'看起来也很讨厌。数组是零索引的。 – 2013-02-16 18:50:16

+0

@ H2CO3是的,我最初错过了 - 谢谢! – us2012 2013-02-16 18:53:12