号码转换声明

时间:2015-10-08 14:25:19

标签: c# switch-statement

所以我试图制作这个简单的程序,但是当我运行程序时使用switch语句,无论我输入什么,我总是得到默认答案。如何才能将它输入到我输入数字的正确陈述的位置?

int number;

Console.WriteLine("Enter a number between 0 and 50: ");
number = int.Parse(Console.ReadLine());

switch (number )
{
     case 1:
        Console.WriteLine("Do you not know how to count? That's more than 50!");
        break;
     case 2:
         Console.WriteLine("Did I say you could choose a number below 0?");                 
         break;
     default:
         Console.WriteLine("Good job smarty pants!");
         break;
}        
Console.ReadLine();

3 个答案:

答案 0 :(得分:6)

嗯,只有ifelse if

  if (number > 50)
    Console.WriteLine("Do you not know how to count? That's more than 50!");
  else if (number < 0) 
    Console.WriteLine("Did I say you could choose a number below 0?");           
  else
    Console.WriteLine("Good job smarty pants!");

答案 1 :(得分:0)

不幸的是,在这种情况下,您正在尝试将工具用于不适合的用途。案例实际上是针对解决方案空间的不同案例,而不是连续案例。 (答案之间的差异可以是-1或1,答案可以是&lt; 0和&gt; 0)。话虽这么说,我支持用户Dmitry Bychenko的回答,该回答声明使用ifelse if来完成此任务。我相信你可以设计一种使用switch声明的方法,但这就像使用锤子的背面来铺地板一样。

答案 2 :(得分:0)

你也可以试试这个:

int number = 12;
Dictionary<Func<int, bool>, Action> dict = new Dictionary<Func<int, bool>, Action>
            {
                {x => x < 0, () => Console.WriteLine("Smaller than 0")},
                {x => x > 50, () => Console.WriteLine("Greater than 50")},
                {x => (x >= 0 && x <= 50), () => Console.WriteLine("Between 0 and 50")}
            };

dict.First(kvp => kvp.Key(number)).Value();