2013-02-28 25 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++) 
       ^