C# if-else語句

2019-10-16 23:17:20

一個if語句可以跟隨一個可選的else語句,當布林表示式為false時,則將執行else塊中的程式碼。

語法

C# 中if...else語句的語法是:

if(boolean_expression)
{
   /* statement(s) will execute if the boolean expression is true */
}else
{
   /* statement(s) will execute if the boolean expression is false */
}

如果布林表示式(boolean_expression)的值為true,則執行if程式碼塊,否則執行else程式碼塊。

流程圖

範例程式碼

using System;
namespace DecisionMaking
{
   class Program 
   {
      static void Main(string[] args)
      {
         /* local variable definition */
         int a = 199;

         /* check the boolean condition */
         if (a < 10)
         {
            /* if condition is true then print the following */
            Console.WriteLine("a is less than 10");
         }
         else
         {
            /* if condition is false then print the following */
            Console.WriteLine("a is not less than 10");
         }
         Console.WriteLine("value of a is : {0}", a);
         Console.ReadLine();
      }
   }
}

當編譯和執行上述程式碼時,會產生以下結果:

a is not less than 19;
value of a is : 199

if…else if…else語句

一個if語句可以跟隨一個可選的else if...else語句,這對於使用單個if...else if語句來測試各種條件非常有用。

當使用ifelse if, else語句時要注意以下幾點 -

  • 一個if語句可以有零個或一個else語句,但它必須放在else if語句之後。
  • 一個if語句可以有零到多個else if語句,但必須放在else語句之前。
  • 一旦有一個else if條件測試成功,剩下的其他if elseelse將不會再被測試。

語法

C# 中if...else if...else語句的語法是:

if(boolean_expression 1)
{
   /* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2)
{
   /* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3)
{
   /* Executes when the boolean expression 3 is true */
}
else 
{
   /* executes when the none of the above condition is true */
}

範例

using System;
namespace DecisionMaking
{
    class Program
    {
        static void Main(string[] args)
        {
            /* local variable definition */
            int a = 199;

            /* check the boolean condition */
            if (a == 19)
            {
                /* if condition is true then print the following */
                Console.WriteLine("Value of a is 19");
            }
            else if (a == 29)
            {
                /* if else if condition is true */
                Console.WriteLine("Value of a is 29");
            }
            else if (a == 39)
            {
                /* if else if condition is true  */
                Console.WriteLine("Value of a is 39");
            }
            else
            {
                /* if none of the conditions is true */
                Console.WriteLine("None of the values is matching");
            }
            Console.WriteLine("Exact value of a is: {0}", a);
            Console.ReadLine();
        }
    }
}

當編譯和執行上述程式碼時,會產生以下結果:

None of the values is matching
Exact value of a is: 199