2012-10-20 219 views
0

我刚写了一个简单的C#代码来计算一个数字的阶乘,但程序被卡在了姓氏上。有人可能为什么它卡住了吗?为什么这个while循环卡住了?

感谢,

10min为单位

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")); 
     } 
    } 
} 

} `

+5

这不找到[factorial](http://en.wikipedia.org/wiki/Factorial)... – ppeterka

+4

与调试器一起代码是你的朋友! –

回答

8

看看你while条件:

while ((ans != "Y") || (ans != "y") || (ans != "N") || (ans != "n")) 

为了突围,这些子的所有 - CON分配必须是错误的(因此总体价值是错误的)。

第一个条件是真实的唯一方法是,如果ans是“Y” ...这意味着它绝对不会等于“Y” ......

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

while (!(ans == "Y" && ans == "y" && ans == "N" && ans == "n")) 

它将必须是一个非常特殊的字符串,以等于所有四个值。

实际上想:

while (ans != "Y" && ans != "y" && ans != "N" || ans != "n") 

换句话说,继续前进而值不等于所需值的任何。 (另一种方法是将一组“好的答案”的...

+0

好吧我想我错过了一些东西。像这样读取?如果并不等于“Y”或“y”等,则打破循环。Meani如果它等于其中一个,它应该打破? –

+2

aka [De Morgan's laws](http://en.wikipedia.org/wiki/De_Morgan's_laws):-) – fvu

+0

@Omin:它被称为“while循环”是有原因的。 **条件满足时重复循环**。这反过来又意味着,一旦**不满意**,就打破循环。 – Lou

0
 do { 
      string ans = Console.ReadLine(); 
      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")); 
0

我会做这样的事情:

bool isValid = false; 

     do 
     { 

      if(ans == "Y" || ans == "y") { 
       play = true; 
       isValid = true; 
       //break; 
      } 
      else if(ans == "N" || ans == "n") { 
       play = false; 
       isValid = true; 
       //break; 
      } 
      else 
      { 
       Console.Write("You have entered an invalid answer. Please choose from either Y or N: "); 
       ans = Console.ReadLine(); 
       isValid = false; 
      } 
     }while(isValid == false); 

相关小提琴:https://dotnetfiddle.net/bxHY27