多个if语句或else-if语句

时间:2014-09-20 21:13:40

标签: c# if-statement

在编写多个if语句而不仅仅是一个语句,然后添加else-if之后是否有区别?

喜欢这里:

        Console.WriteLine("Guess the number from 1/5");
        int number = int.Parse(Console.ReadLine());
        if (number == 1)
        {
            Console.WriteLine("You guessed wrong");
        }
        if (number == 2)
        {
            Console.WriteLine("You guessed wrong");
        }
        /* else if (number == 2)
        {
            Console.WriteLine("You guessed wrong");
        }
         * .......up to number 5
         */
        if (number == 3)
        {
            Console.WriteLine("You guessed wrong");
        }
        if (number == 4)
        {
            Console.WriteLine("You guessed wrong");
        }
        if (number == 5)
        {
            Console.WriteLine("You're right!");
        }
        Console.ReadKey();

我知道有更好的方式来写这个,但差异是唯一对我来说重要的事情。它可能会对绩效产生影响......

3 个答案:

答案 0 :(得分:2)

当你使用多个if时,你将逐个检查它们。如果您在输入其中一个时使用if,else if,则不会再进行检查。在您的情况下,最好使用else if,因为数字只能包含其中一个值。

            Console.WriteLine("Guess the number from 1/5");
            int number = int.Parse(Console.ReadLine());
            if (number == 1)
            {
                Console.WriteLine("You guessed wrong");
            }
            else if (number == 2)
            {
                Console.WriteLine("You guessed wrong");
            }             
            else if (number == 3)
            {
                Console.WriteLine("You guessed wrong");
            }
            else if (number == 4)
            {
                Console.WriteLine("You guessed wrong");
            }
            else if (number == 5)
            {
                Console.WriteLine("You're right!");
            }
            else
            {
                Console.WriteLine("Wrong guess");
            }
            Console.ReadKey();

`如果你有更好的表现,还有别的!你也可以通过调试检查这些东西!你应该学会使用它!

答案 1 :(得分:0)

一般来说,避免使用巨大的if-else语句是使用switch子句

switch(number)
{
    case 1:
        // this part will run if number is 1
        break; // break is required after cases

    case 2:
        // this part will run if number is 2
        break;

    case 3:
    case 4:
        // you can also join cases together
        // this part will run if number is either 3 or 4
        break;

    default:
        // the default case runs when no case was matched
        break;
}

在您的情况下,使用switch可以简化您的代码

switch (number)
{
    default:
        Console.WriteLine("You guessed wrong");
        break;

    case 5:
        Console.WriteLine("You're right!");
        break;
}

答案 2 :(得分:0)

在这种情况下,您可以执行以下操作:

  Console.WriteLine("Guess the number from 1/5");
  int number = int.Parse(Console.ReadLine());
  var result = number == 5  ? "You're right!" : "You guessed wrong";

  Console.WriteLine(result );


  Console.ReadKey();