[英]C#: WHILE loop continues, seemingly ignoring the condition
我正在編寫一個基本的瑣事程序來幫助自己熟悉 C#。 我處於開發的早期階段,遇到了一個我很難理解的問題。 這是代碼,然后是我迄今為止嘗試過的代碼。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TriviaProject
{
internal class Program
{
static void Main(string[] args)
{
var q1 = "x";
int totalCorrect = 0;
int totalIncorrect = 0;
Console.WriteLine("Question 1: What is the answer?");
Console.WriteLine("A. Correct Answer");
Console.WriteLine("B. Incorrect Answer");
Console.WriteLine("C. Incorrect Answer");
while (q1 != "A" || q1 != "B" || q1 != "C")
{
q1 = Console.ReadLine();
switch (q1)
{
case "A":
Console.WriteLine("{0} is the correct Answer!", q1);
++totalCorrect;
break;
case "B":
Console.WriteLine("{0} is not correct.", q1);
++totalIncorrect;
break;
case "C":
Console.WriteLine("{0} is not correct.", q1);
++totalIncorrect;
break;
default:
Console.WriteLine("{0} is not a valid entry. A, B or C.", q1);
break;
}
}
Console.WriteLine("You got {0} correct and {1} incorrect. Your total score is: ", totalCorrect, totalIncorrect);
}
}
}
期望的行為如果答案是 A,則 totalCorrect 計數應增加並顯示。 如果答案是 B 或 C,則總不正確計數應增加並顯示。
到目前為止嘗試過
我還嘗試了使用 CONTINUE 而不是 BREAK 的不同組合。
如果有人可以解釋這種行為,將不勝感激。
從邏輯上講,您的 while 循環是while (true)
。
q1 != "A"
如果 q1 為 A,則為假,否則為真
q1 != "B"
如果 q1 為 B,則為假,否則為真
因為 A 不是 B,所以這兩個陳述不可能同時為假,所以你有
由於 true-or-anything 為 true,因此您的條件為true
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.