随机数猜谜游戏

3 c# numbers

我正在做一个随机数猜测游戏,计算机认为是1-100之间的数字.然后它会询问你它是什么,并告诉你你是对还是错.但是,每当我调试时,由于某种原因它会说它高于或低于实际随机数.此外,它同时说出其中两个陈述.另外,我不知道怎么说这个人已经猜了多少次.这是我不成功的代码.

static void Main(string[] args) 
{
    Random random = new Random();

    int returnValue = random.Next(1, 100);
    int Guess = 0;

    Console.WriteLine("I am thinking of a number between 1-100.  Can you guess what it is?");

    while (Guess != returnValue)
    {
        Guess = Convert.ToInt32(Console.Read());

        while (Guess < returnValue)
        {
            Console.WriteLine("No, the number I am thinking of is higher than " + Guess + " .  Can you guess what it is?");
            Console.ReadLine();

        }
        while (Guess > returnValue)
        {
            Console.WriteLine("No, the number I am thinking of is lower than " + Guess + " .  Can you guess what it is");
            Console.ReadLine();
        }
    }
    while (Guess == returnValue)
    {
        Console.WriteLine("Well done! The answer was " + returnValue);
        Console.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

OnR*_*lve 5

你正在使用很多不必要的迭代.while语句采用布尔条件,就像IF语句一样.

static void Main(string[] args)

{

Random random = new Random();

int returnValue = random.Next(1, 100);

        int Guess = 0;

        Console.WriteLine("I am thinking of a number between 1-100.  Can you guess what it is?");

        while (Guess != returnValue)
        {
            Guess = Convert.ToInt32(Console.Read());

            if (Guess < returnValue)
            {
                Console.WriteLine("No, the number I am thinking of is higher than " + Guess + ". Can you guess what it is?");
            }
            else if (Guess > returnValue)
            {
                Console.WriteLine("No, the number I am thinking of is lower than " + Guess + ". Can you guess what it is?");
            }

        }

        Console.WriteLine("Well done! The answer was " + returnValue);
        Console.ReadLine();

}
Run Code Online (Sandbox Code Playgroud)

  • 如果你第一次猜对了,它会问你"你能猜出它是什么吗?" 再次. (2认同)