简体   繁体   English

数字游戏中的循环问题

[英]Looping Issue in Number Game

I'm trying to get back to the basics, using a while loop and a bool to keep the guessing game going is cleaner and helps me learn how to usue booleans better.我试图回到基础知识,使用 while 循环和 bool 来保持猜谜游戏的进行更清晰,并帮助我学习如何更好地使用布尔值。 But this game just sticks into an infinite loop?但是这个游戏只是陷入了无限循环? Is there anyway to fix this, I'm sure I'm missing something obvious有没有办法解决这个问题,我确定我遗漏了一些明显的东西

    namespace Guess_Number_V2
{
    class Program
    {
        static void Main(string[] args)
        {
            Random rand = new Random();
            int randNum = rand.Next(1, 11);
            int guessCount = 0;
            int userScore = 10;
            int userGuess;
            int perGuess = 1;
            bool correctGuess = false;

            Console.WriteLine("Enter a number between 1 and 10");

            userGuess = int.Parse(Console.ReadLine());

            while (correctGuess == false)
            {
                if (userGuess == randNum)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    userScore -= perGuess;
                    Console.WriteLine("Your guess was right, the number was {0}! Total score is {1} and you had {2} attempts.", randNum, userScore, guessCount);

                    correctGuess = true;


                }

                if (userGuess > randNum)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Wrong guess again, to high!");
                    userScore -= perGuess;
                    correctGuess = false;

                }

                else if (userGuess < randNum)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Wrong guess again, to low!");
                    userScore -= perGuess;
                    correctGuess = false;


                }
            }
        }
    }
}

You need to move the prompt inside the loop or you'll never get a new userGuess .您需要将提示移到循环内,否则您将永远得不到新的userGuess That's why you are getting an infinite loop.这就是为什么你会得到一个无限循环。

Console.WriteLine("Enter a number between 1 and 10");

while (correctGuess == false)
{
    userGuess = int.Parse(Console.ReadLine());
    // ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM