为什么这个while循环卡住了?

Cha*_*Han 0 c# while-loop do-while

我刚刚编写了一个简单的c#代码来计算数字的阶乘,但程序却被卡在姓氏上.有人为什么会被卡住?

谢谢,

OMIN

using System;

//1. Write a program which finds the factorial of a number entered by the user.

namespace Beginner1{

class ProblemOne
{
    static void Main (string[] args)
    {
        bool play = true;
        while ( play ) {
            Console.Write ("Type in the number you would like to find Factorial of: ");
            int num = Convert.ToInt16( Console.ReadLine ());
            int sum = 1;
            for (int i = 2; i <= num; i++) {
                sum = sum * i;
            }
            Console.WriteLine ("The Factorial of {0} is {1}", num, sum);
            Console.Write ( "Would you like to play again? (Y or N): " );
            string ans = Console.ReadLine();
            do {
                if( ans == "Y" || ans == "y" )  {
                    play = true;
                    //break;
                }
                else if( ans == "N" || ans == "n" ) {
                    play = false;
                    //break;
                }
                else
                {
                    Console.Write( "You have entered an invalid answer. Please choose from either Y or N: ");
                    ans = Console.ReadLine();
                }
            } while ( (ans != "Y") || (ans != "y") || (ans != "N") || (ans != "n") );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

}

Jon*_*eet 8

看看你的while情况:

while ( (ans != "Y") || (ans != "y") || (ans != "N") || (ans != "n") )
Run Code Online (Sandbox Code Playgroud)

为了突破,所有这些子条件必须是假的(因此整体值为假).

第一个条件成立的唯一方法是if ans是"Y"......这意味着它绝对不会等于"y"......

换句话说,你的循环等于:

while (!(ans == "Y" && ans == "y" && ans == "N" && ans == "n"))
Run Code Online (Sandbox Code Playgroud)

它必须是一个非常特殊的字符串才能等于所有四个值.

真的想要:

while (ans != "Y" && ans != "y" && ans != "N" || ans != "n")
Run Code Online (Sandbox Code Playgroud)

换句话说,在值不等于任何所需值时继续前进.(另一种方法是保留一套"好的答案"......

  • 又名[De Morgan的法律](http://en.wikipedia.org/wiki/De_Morgan's_laws):-) (2认同)