一个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
语句来测试各种条件非常有用。
当使用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