带有多个||(Or)语句的C#While循环不起作用



我有以下C#代码

int amount_guesses = 2;
int c_answer = 4;
int u_answer = 0;
Console.WriteLine("Guessing Game");
Console.WriteLine("*Hint:The number is between 1 and 5");
Console.WriteLine("*Hint:You only get 2 guesses");
while (u_answer != c_answer || amount_guesses != 0)
{
u_answer = Convert.ToInt32(Console.ReadLine());
amount_guesses = amount_guesses-1;
if (u_answer == c_answer)
{
Console.WriteLine("Well Done that is the Correct Number");
}
else
{
Console.WriteLine("Wrong Number!Try again.You have {0} trys left", amount_guesses);
}
}
Console.WriteLine("Press any key to close");
Console.ReadLine();

但当不满足while语句中的要求时,它并没有跳出循环
我也试过

while ((u_answer != c_answer) || (amount_guesses != 0))

但它仍然不起作用,我最终将逻辑改为:

int amount_guesses = 2;
int c_answer = 4;
int u_answer = 0;
Console.WriteLine("Guessing Game");
Console.WriteLine("*Hint:The number is between 1 and 5");
Console.WriteLine("*Hint:You only get 2 guesses");
while (u_answer != c_answer && amount_guesses != 0)
{
u_answer = Convert.ToInt32(Console.ReadLine());
amount_guesses = amount_guesses-1;
if (u_answer == c_answer)
{
Console.WriteLine("Well Done that is the Correct Number");
amount_guesses = 0;
}
else
{
Console.WriteLine("Wrong Number!Try again.You have {0} trys left", amount_guesses);
}
}
Console.WriteLine("Press any key to close");
Console.ReadLine();

这很好,但我想知道为什么我使用||的顶部代码不起作用?

只要满足条件,while循环就会继续。在您的情况下,只要玩家还没有猜到数字,并且还有猜测,您就想继续循环。您应该使用&&(逻辑AND(条件,而不是||:

while (u_answer != c_answer && amount_guesses != 0)
{
// Here ----------------^

在布尔逻辑中使用否定时,这是一个常见的(ish(问题。OR听起来应该是正确的,因为它符合英语的说话方式,但实际上AND是你想要的。

我试着总是写条件测试等式,然后否定它,所以不是:

u_answer != c_answer && amount_guesses != 0

你可以写:

!(u_answer == c_answer || amount_guesses == 0)

这是相同的条件。

看看德莫加姆斯定律,也更容易被记忆为

换行,更改符号

相关内容

  • 没有找到相关文章

最新更新