我遇到了一个程序问题。我需要比较组合的数量,如果它们相同,则值越高。否则,如果组合的数量相同且值相同,则为平局。在这里我到目前为止。
int[] player1 = new int[6];
int[] player2 = new int[6];
Random rndGen = new Random();
for (int i = 0; i < 5; i++)
{
int diceRoll = 0;
diceRoll = rndGen.Next(6);
player1[diceRoll]++;
Console.WriteLine("Computer rolled: {0}", diceRoll + 1);
}//end for
for (int i = 0; i < 5; i++)
{
int diceRoll = 0;
diceRoll = rndGen.Next(6);
player2[diceRoll]++;
Console.WriteLine("You rolled: {0}", diceRoll + 1);
}//end for
int maxPlayer1 = 0, maxPlayer2 = 0;
for (int i = 1; i < 5; i++)
{
if (player1[i] > player1[maxPlayer1]) maxPlayer1 = i;
if (player2[i] > player2[maxPlayer2]) maxPlayer2 = i;
}//end for
if (player1[maxPlayer1] > player2[maxPlayer2])
Console.WriteLine("Computer won with {0} of a kind", player1[maxPlayer1], maxPlayer1 + 1);
else
if (player2[maxPlayer2] > player1[maxPlayer1])
Console.WriteLine("You won with {0} of a kind", player2[maxPlayer2], maxPlayer2 + 1);
else
Console.WriteLine("Tie");
}//end main
}
}
答案 0 :(得分:1)
player1[diceRoll]++
真的是你的意思吗?
答案 1 :(得分:1)
乍看之下,您应该检查以下内容:
for (int i = 1; i < 5; i++)
这个循环将执行4次,其中i = 1,2,3,4。这几乎肯定不是你想要做的。
数组是零索引的。这意味着第一个值位于索引0,第二个值位于索引1,等等。对于长度为6的数组,最后一个值将位于索引5处。
使用格式化字符串时,第一个参数是格式,然后每个其他参数都引用一个数字,从0开始。所以对于这一行:
Console.WriteLine("You won with {0} of a kind", player2[maxPlayer2], maxPlayer2 + 1);
从不使用参数maxPlayer2 + 1
。
答案 2 :(得分:0)
我认为你在第三个for循环中有一个错误:
int maxPlayer1 = 0, maxPlayer2 = 0;
for (int i = 1; i < 5; i++)
{
if (player1[i] > player1[maxPlayer1]) maxPlayer1 = i;
if (player2[i] > player2[maxPlayer2]) maxPlayer2 = i;
}//end for
应该是:
int maxPlayer1 = 0, maxPlayer2 = 0;
for (int i = 0; i < 6; i++)
{
if (player1[i] > player1[maxPlayer1]) maxPlayer1 = i;
if (player2[i] > player2[maxPlayer2]) maxPlayer2 = i;
}//end for