我使用一些代码,然后在循环中再次使用它.它看起来很丑,有办法改善它吗?

本文关键字:看起来 代码 然后 循环 | 更新日期: 2023-09-27 17:50:39

我开始学习c#。我写了一个简单的猜数程序。它可以工作,但是我在循环之前使用一些代码,然后在循环中重用它。一定有更好的办法。

using System;
namespace Guessthenumber
{
class Program
{
    static void Main()
    {
        Random rnd = new Random();
        string guess;
        int yourguess;
        int dice = rnd.Next(1, 7);
        Console.WriteLine("Guess a number between 1 and 6");
        guess = Console.ReadLine();
        yourguess = int.Parse(guess);

这里是我在循环中重复的模式。有办法避免这种情况吗?

        if (yourguess > dice)
        {
            Console.WriteLine("Lower");
        }
        if (yourguess < dice)
        {
            Console.WriteLine("Higher");
        }
        if (yourguess == dice)
        {
            Console.WriteLine("Correct!");
        }
        while (yourguess != dice)
        {

          guess = Console.ReadLine();
          yourguess = int.Parse(guess);
            if (yourguess > dice)
            {
                Console.WriteLine("Lower");
            }
            if (yourguess < dice)
            {
                Console.WriteLine("Higher");
            }
            if (yourguess == dice)
            {
                Console.WriteLine("Correct!");
            }
        }
        Console.WriteLine("Press enter to exit");
        Console.ReadLine();
    }
}
}

我使用一些代码,然后在循环中再次使用它.它看起来很丑,有办法改善它吗?

使用do, while循环代替while。这样,代码变成:

static void Main()
{
    Random rnd = new Random();
    string guess;
    int yourguess;
    int dice = rnd.Next(1, 7);
    Console.WriteLine("Guess a number between 1 and 6");
    do
    {
        guess = Console.ReadLine();
        yourguess = int.Parse(guess);
        if (yourguess > dice)
        {
            Console.WriteLine("Lower");
        }
        if (yourguess < dice)
        {
            Console.WriteLine("Higher");
        }
        if (yourguess == dice)
        {
            Console.WriteLine("Correct!");
        }
    } while (yourguess != dice);
    Console.WriteLine("Press enter to exit");
    Console.ReadLine();
}

是的,使用do-while loop代替:

do
{
    // Repeated stuff
} while (yourguess != dice);