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

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

     playerPositions[i] = NextMove;
}

我在这个 for 循环中遇到了一些麻烦。有没有办法让我做到这一点:

NextMove = playerPositions[i] + DiceThrow();

只在for循环中运行一次?

4

3 回答 3

2

您可以包含一个flagcounter与一个if块组合。

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

firstIteration( bool firstIteration)的另一种方法,

firstIteration = false; 

....

for (...)
{
    if (firstIteration)
    {
        NextMove = playerPositions[i] + DiceThrow();
        firstIteration = !firstIteration; // Toggle the flag 
    }
}
于 2012-11-02T23:26:23.797 回答
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;

    }
于 2012-11-02T23:28:00.020 回答
2

您应该将该行移出循环。

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

     playerPositions[i] = NextMove;
}
于 2012-11-03T02:47:20.890 回答