2013-02-28 41 views
0

我正在試圖做一個骰子投擲者在跟蹤有多少獨特的數字顯示。例如(1 2 3 3 1 5 = 4個唯一編號,1 1 1 1 1 1 = 1個唯一編號,1 2 3 4 5 6 = 6個唯一編號)。但每次它只是返回一個「0」的數量唯一的數字。誰能幫忙?獨特的骰子計數器不能正常工作(初學者)

#include <iostream> 
#include <cstdlib> 
#include <ctime> 
using namespace std; 

int numberGenerator()  //generates 1-6 
{ 
int x = (rand() % 6) + 1; 
return x; 
} 

int diceCounter() 
{ 

int counter[6] = {0,0,0,0,0,0}; 

for (int i = 0; i > 6; i++) 
    { 
    int k = numberGenerator();  //records if the dice number has been rolled 
     if (k == 1) 
      counter[0] = 1; 
     if (k == 2) 
      counter[1] = 1; 
     if (k == 3) 
      counter[2] = 1; 
     if (k == 4) 
      counter[3] = 1; 
     if (k == 5) 
      counter[4] = 1; 
     if (k == 6) 
      counter[5] = 1; 
    } 
return counter[0]+counter[1]+counter[2]+counter[3]+counter[4]+counter[5]; 
}      //returns amount of unique dice numbers 


int main() 
{ 
srand(time(NULL)); 
cout << diceCounter() << endl; 


} 
+1

嘗試'counter [k-1] = 1'仍然會有同樣的問題,但代碼會更短。 – John3136 2013-02-28 01:09:00

回答

2

for(int i = 0; i < 6; i++),而不是for(int i = 0; i > 6; i++)

目前您的循環永遠不會執行,因爲6不大於0和少for()條件失敗 - 這就是爲什麼你得到全0。

for(initializer; if-this-condition-is-true-then-execute-for-loop-else-dont ; increment) < - 考慮循環的一般方法!

1

for循環的條件是反向的,所以你的循環將永遠不會運行:

for (int i = 0; i > 6; i++) 
       ^