2013-02-16 172 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