C#中使用||运算符时While循环无限循环的原因咨询
问题:while循环使用||导致无限循环的原因
你的C#代码如下:
namespace GuestBook { internal class GuestTracker { public static (string fullName, int guestCount) NameLog() { int guestCount; Console.Write("Welcome to the Cliffview Venue, " + "Hubbard's Wedding check in, what is your first and last name? "); string fullName = Console.ReadLine(); Console.Write($"\nHello {fullName} how many people will be joining you today? "); string guestCountText = Console.ReadLine(); while (int.TryParse(guestCountText, out guestCount) == false) { Console.Write("\nSorry that wasn't a vaild number of guests, please entar a count using only the 0-9 characters: "); guestCountText = Console.ReadLine(); } Console.Write($"So we have a total of {guestCount} guests, is this correct? "); string correctCount = Console.ReadLine(); string no; while((no = correctCount.ToLower()) != "yes" || no != "no") { Console.Write("\nI'm sorry, was that a yes or no? "); correctCount = Console.ReadLine(); } if(correctCount.ToLower() == "no") { Console.Clear(); Console.Write("\nOkay let's start over then."); NameLog(); } return (fullName, guestCount); } } }
无限循环的原因
你在第二个while循环里用了||(逻辑或)运算符,这个逻辑的核心问题是:无论用户输入什么,循环条件永远为true。
举两个关键场景就能看明白:
- 当用户输入
yes时,no != "yes"是false,但no != "no"是true,false || true的结果是true,循环继续 - 当用户输入
no时,no != "yes"是true,但no != "no"是false,true || false的结果还是true,循环继续
不管输入是yes、no还是其他内容,这个条件都会成立,循环根本停不下来,自然就陷入无限循环了。
你想要的逻辑是「当输入既不是yes也不是no时,继续循环」,这时候应该用&&(逻辑与)运算符,把条件改成:
while((no = correctCount.ToLower()) != "yes" && no != "no")
这样只有当输入既不是yes也不是no的时候,循环才会继续;只要输入yes或no,条件就会变成false,循环终止。
内容的提问来源于stack exchange,提问作者Zathus89
相关产品推荐
相关产品推荐

