【发布时间】:2021-08-24 02:22:06
【问题描述】:
while 循环
public static bool Authentication()
{
bool isAuthenticated = false;
int count = 4;
while (isAuthenticated = false && count > 0)
{
Console.WriteLine("Please insert your 4 digit PIN");
string pin = Console.ReadLine();
if (pin == "1704")
{
isAuthenticated = true;
return isAuthenticated;
}
else
{
count--;
Console.WriteLine($"Wrong PIN: {count} Input remained ");
}
}
return isAuthenticated;
}
我一直无法理解,当调试器进入 while 循环时,它并没有执行它。可能是当时的情况不符合逻辑。
【问题讨论】:
-
您是否考虑过在代码上使用调试器来找出问题?
-
=是赋值运算符。==是比较运算符。 -
正如其他人指出的那样,NOT 运算符 (
!) 更适合检查布尔值的 false-ness。另一个风格上的小问题:变量名count通常是向上计数,而不是向下计数。考虑将其命名为triesLeft以使其含义更清晰 -
你可以只使用while (count > 0),因为你在isAuthenticated = true时返回;
标签: c# while-loop return boolean