一个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
以上就是小编为大家整理发布的“C语言学习:C# if:else语句,这些要记住!”一文,更多相关内容尽在开课吧广场C++教程频道。
免责声明:本站所提供的内容均来源于网友提供或网络搜集,由本站编辑整理,仅供个人研究、交流学习使用。如涉及版权问题,请联系本站管理员予以更改或删除。
