簡體   English   中英

C#:WHILE 循環繼續,似乎忽略了條件

[英]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,則總不正確計數應增加並顯示。

到目前為止嘗試過

  • 如果我從 WHILE 語句中刪除 B 和 C,如果我回答“A”,程序將按預期工作
  • 為了糾正上述情況,我在 WHILE 語句中添加了 B 和 C 假設我在回答 B 和 C 時會看到類似的行為
  • 當 B 和 C 包含在 While 語句中時,我得到正確的反饋(正確或不正確),但無論我輸入什么,循環都會繼續(程序永遠不會轉到結果)

我還嘗試了使用 CONTINUE 而不是 BREAK 的不同組合。

如果有人可以解釋這種行為,將不勝感激。

從邏輯上講,您的 while 循環是while (true)

q1 != "A"

如果 q1 為 A,則為假,否則為真

q1 != "B"

如果 q1 為 B,則為假,否則為真

因為 A 不是 B,所以這兩個陳述不可能同時為假,所以你有

  • 一)假|| 真的
  • B) 真|| 錯誤的
  • 其他) 真 || 真的

由於 true-or-anything 為 true,因此您的條件為true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM