一個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
語句來測試各種條件非常有用。
當使用if
,else if
, else
語句時要注意以下幾點 -
if
語句可以有零個或一個else
語句,但它必須放在else if
語句之後。if
語句可以有零到多個else if
語句,但必須放在else
語句之前。else if
條件測試成功,剩下的其他if else
或else
將不會再被測試。 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