if语句后面可以跟随可选的else语句,该语句在布尔表达式为false时执行。
C#中if.else语句的语法是-
if(boolean_expression) { /* 如果布尔表达式为真,则将执行语句 */ } else { /* 如果布尔表达式为假,语句将执行 */ }
using System; namespace DecisionMaking { class Program { static void Main(string[] args) { /* 局部变量定义 */ int a = 100; /* 检查布尔条件 */ if (a < 20) { /* 如果条件为真,则打印以下内容 */ Console.WriteLine("a is less than 20"); } else { /* 如果条件为假,则打印以下内容 */ Console.WriteLine("a is not less than 20"); } Console.WriteLine("value of a is : {0}", a); Console.ReadLine(); } } }
编译并执行上述代码时,将生成以下输出-
a is not less than 20; value of a is : 100
If语句后面可以跟随可选的Else If.Else语句,这对于使用单个If.Else If语句测试各种条件非常有用。
链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/if-else-statement-in-csharp.html
来源:LearnFk无涯教程网
C#中if.else语句的语法是-
if(boolean_expression 1) { /* 当布尔表达式 1 为真时执行 */ } else if( boolean_expression 2) { /* 当布尔表达式 2 为真时执行 */ } else if( boolean_expression 3) { /* 当布尔表达式 3 为真时执行 */ } else { /* 当上述条件都不为真时执行 */ }
using System; namespace DecisionMaking { class Program { static void Main(string[] args) { /* 局部变量定义 */ int a = 100; /* 检查布尔条件 */ if (a == 10) { /* 如果条件为真,则打印以下内容 */ Console.WriteLine("Value of a is 10"); } else if (a == 20) { /* if else if 条件为真 */ Console.WriteLine("Value of a is 20"); } else if (a == 30) { /* if else if 条件为真 */ Console.WriteLine("Value of a is 30"); } else { /* 如果没有一个条件为真 */ 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: 100
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)