2012-11-02 61 views
1
for (int i = 0; i < NumberOfPlayers; i++) 
{ 
    NextMove = playerPositions[i] + DiceThrow(); 

    while (RocketInSquare(NextMove) == true) 
      playerPositions[i] = NextMove++; 

    playerPositions[i] = NextMove; 
} 

我在循環中遇到了一些麻煩。有沒有辦法讓我的線:1D陣列中的條件聲明

NextMove = playerPositions[i] + DiceThrow(); 

只在for循環運行一次?

+0

1.'if(i == 0)'2.將它移出循環體 – zerkms

+0

它應該只對for循環的每次迭代運行一次。 – itsme86

+0

出於好奇,圍繞有關陳述的括號是什麼? – Charleh

回答

2

你應該移到該行圈外。

NextMove = playerPositions[0] + DiceThrow(); 
for (int i = 0; i < NumberOfPlayers; i++) 
{ 
    while (RocketInSquare(NextMove)) 
      NextMove++; 

    playerPositions[i] = NextMove; 
} 
+0

只要確保數組不是大小0。 – Servy

2

您可以包含flagcounter結合if塊。

if (counter == 0) 
{ 
    NextMove = playerPositions[i] + DiceThrow(); 
    counter++; 
} 

firstIterationbool firstIteration)的另一種方法,

firstIteration = false; 

.... 

for (...) 
{ 
    if (firstIteration) 
    { 
     NextMove = playerPositions[i] + DiceThrow(); 
     firstIteration = !firstIteration; // Toggle the flag 
    } 
} 
+0

好吧,這太棒了。幾分鐘前我想到了這一點。感謝你的時間:) –

2

保持一個標誌

bool flag = false;  
    for (int i = 0; i < NumberOfPlayers; i++) 
    { 
    if(!flag) 
    { 
     NextMove = playerPositions[i] + DiceThrow(); 
     flag = true; 
    } 

    while (RocketInSquare(NextMove) == true) 
     { 
      playerPositions[i] = NextMove++; 

     } 
     playerPositions[i] = NextMove; 

    }