我写了下面的代码,这基本上是一个“猜数字”游戏。它有效,但我有太多缩进的“如果”。我怎样才能使这段代码更干净、更高效?
Random rndm = new Random();
int rndmNumber = rndm.Next(0, 10);
int chances = 3;
while (chances >= 0)
{
Console.WriteLine("Enter a number: ");
int userNumber = Convert.ToInt32(Console.ReadLine());
{
if (userNumber != rndmNumber)
{
if (chances == 1)
{
Console.WriteLine("You last chance: ");
}
if (chances != 0)
{
Console.WriteLine("Try again!!");
}
if (chances == 0)
{
Console.WriteLine("You Lost!!");
}
Console.WriteLine("You have " + chances + " chances");
chances--;
}
else if (userNumber == rndmNumber)
{
Console.WriteLine("YOu Won!!");
chances--;
break;
}
}
}