C#中的if if...和if-else if

编写多个if和编写多谢if-esle if结果是不一样的,下面以实例说明:

一、多个if-else if:

 1 static void Main(string[] args)
 2         {
 3             int a = 5;
 4             if (a > 1)
 5             {
 6                 Console.WriteLine("a大于1");
 7             }
 8             else if (a > 2)
 9             {
10                 Console.WriteLine("a大于2");
11             }
12             else if (a > 3)
13             {
14                 Console.WriteLine("a大于3");
15             }
16             else if (a > 6)
17             {
18                 Console.WriteLine("a大于6");
19             }
20             else
21             {
22                 Console.WriteLine("xx");
23             }
24         }

输出:

a大于1

二、多个 if-if

 1         static void Main(string[] args)
 2         {
 3             int a = 5;
 4             if (a > 1)
 5             {
 6                 Console.WriteLine("a大于1");
 7             }
 8             if (a > 2)
 9             {
10                 Console.WriteLine("a大于2");
11             }
12             if (a > 3)
13             {
14                 Console.WriteLine("a大于3");
15             }
16             if (a > 6)
17             {
18                 Console.WriteLine("a大于6");
19             }
20             else
21             {
22                 Console.WriteLine("xx");
23             }
24         }

输出:

a大于1

a大于2

a大于3

xx

三、总结

多个if - if 时,会执行每个if并判断条件;

多个if - else if时,只会执行第一个符合条件的;

else总是与最近的if配对。

原文地址:https://www.cnblogs.com/Drajun/p/7530625.html