c# -我需要添加代码!猜猜数字

本文关键字:代码 添加 数字 | 更新日期: 2023-09-27 18:05:53

我写了一个猜1-100之间的数字游戏。这是我的代码…

class Program
{
    static void Main(string[] args)
    {
        while (true)
        {
            int randno = Newnum(1, 101);
            int count = 1;
            while (true)
            {
                Console.Write("Guess a number between 1 and 100, or press 0 to quit: ");
                int input = Convert.ToInt32(Console.ReadLine());
                if (input == 0)
                    return;
                else if (input < randno)
                {
                    Console.WriteLine("Unlucky, that number is too low - have another go!");
                    ++count;
                    continue;
                }
                else if (input > randno)
                {
                    Console.WriteLine("Unlucky, that number is too high - have another go!");
                    ++count;
                    continue;
                }
                else
                {
                    Console.WriteLine("Well done - you guessed it! The number was {0}.", randno);
                    Console.WriteLine("It took you {0} {1}.'n", count, count == 1 ? "attempt" : "attempts to guess it right");
                    break;
                }
            }
        }
    }
    static int Newnum(int min, int max)
    {
        Random random = new Random();
        return random.Next(min, max);
    }
}

我怎么编辑它,这样如果一个用户接近这个数字,比如在5个数字之内,他们会收到一个消息,说他们接近了?

c# -我需要添加代码!猜猜数字

您可以使用Math.Abs:

int diff = Math.Abs(input - randno);
if(diff <= 5)
{
    // say him that he's close
}