除else语句外,一切都正常运行。一旦数字彼此相等,它就会被跳过。它没有说"你得到它"最后。
//declare variables
int number = 4;
int guessCount = 0;
int guess;
//get first number
Console.WriteLine("Guess a number between 1 and 10:");
guess = Convert.ToInt32(Console.ReadLine());
guessCount = guessCount + 1; //increment counter
while (guess != number) //keep repeating until number is chosen
{
guessCount = guessCount + 1; //increment counter
if (guess < number) //if statement if guess is less than number
{
Console.WriteLine("Your guess is too low.");
}
else if (guess > number) //if statement if guess is more than number
{
Console.WriteLine("Your guess is too high.");
}
else //
{
Console.WriteLine("You got it!!");
}
//end of while to ask for a new guess
Console.WriteLine("Guess again: ");
guess = Convert.ToInt32(Console.ReadLine());
}
//display output
Console.WriteLine("You figured it out in " + guessCount + " guesses.");
Console.ReadLine(); //keep window open
答案 0 :(得分:2)
当它进入while
循环时,表示guess
为!=
number
,此处唯一可能的状态为guess < number
,您已经检查过的guess > number
guess = number
没有意义,因为如果guess
等于number
,它甚至不会进入while
}循环。这就是为什么else
语句永远不会执行的原因,因为else
语句检查的唯一状态是guess == number
。
答案 1 :(得分:2)
while 表达式声明:猜测 !=数字只要用户未键入 4 < / strong>(您的硬编码值)。您在检查 while 表达式之前设置 guess ,因此如果用户键入正确的数字,则while表达式将为false并且将跳过。我在问题的位置评论了你的代码。
//declare variables
int number = 4;
int guessCount = 0;
int guess;
//get first number
Console.WriteLine("Guess a number between 1 and 10:");
// Problem A: user types in 4 -> guess becomes equal to number -> while expression gets false -> while body will not be executed
guess = Convert.ToInt32(Console.ReadLine());
while (guess != number) //keep repeating until number is chosen
{
guessCount = guessCount + 1; //increment counter
if (guess < number) //if statement if guess is less than number
{
Console.WriteLine("Your guess is too low.");
}
else if (guess > number) //if statement if guess is more than number
{
Console.WriteLine("Your guess is too high.");
}
else //
{
Console.WriteLine("You got it!!");
}
//end of while to ask for a new guess
Console.WriteLine("Guess again: ");
// Problem B: user types in 4 -> guess becomes equal to number -> while expression gets false -> loop ends
guess = Convert.ToInt32(Console.ReadLine());
}