如何使这段代码更短、更高效? [已关闭]

问题描述 投票:0回答:0

我写了下面的代码,这基本上是一个“猜数字”游戏。它有效,但我有太多缩进的“如果”。我怎样才能使这段代码更干净、更高效?

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;
        }
    }
}
c# optimization coding-style new-project
© www.soinside.com 2019 - 2024. All rights reserved.