条件语句 目标 区分不同类型的条件语句。 记住创建条件语句的语法。 将条件语句应用于应用程序逻辑中的决策。 简介 有时我们可能希望根据接收到的输入使程序表现出不同的行为。在这种情况下,C# 提供了预先准备决策的方法,以便在满足预设条件后执行特定代码段。这些语句被称为条件语句。 有四种条件语句: 语句 语句 语句 语句 条件语句可以与以下逻辑条件一起使用: 小于: 小于或等于: 大于: 大于或等于: 等于: 不等于: if 语句 if 语句用于在需要满足特定条件时执行命令。如果条件为真,则执行代码。 以下是要创建一个 语句的语法: 下面是一个 if 语句的例子,该语句在 is greater than 时执行字符串。
有时我们可能希望根据接收到的输入使程序表现出不同的行为。在这种情况下,C# 提供了预先准备决策的方法,以便在满足预设条件后执行特定代码段。这些语句被称为条件语句。
有四种条件语句:
if 语句if/else 语句else/if 语句switch 语句条件语句可以与以下逻辑条件一起使用:
a < ba <= ba > ba >= ba == ba != 5if 语句用于在需要满足特定条件时执行命令。如果条件为真,则执行代码。
以下是要创建一个 if 语句的语法:
if (condition) { //code that runs if condition is true }
下面是一个 if 语句的例子,该语句在 10 is greater than 3 时执行字符串。
if (10 > 3) { Console.WriteLine("10 is greater than 3."); }
if/else 语句用于在特定条件失败后确保执行特定命令。
以下是要创建一个 if/else 语句的语法:
if(condition) { //code that runs if condition is met } else { //code that runs if condition is not met }
下面是一个 if/else 语句的例子,该语句判断 4 x 5 is equal to 30. Given that 4 x 5 is equal to 20, the code executes the string within the else 语句。
if(4 x 5 == 30) { Console.WriteLine("The product of 4 x 5 is 30.") } else { Console.WriteLine("The product of 4 x 5 is 20.") }
if/else 语句用于在第一个条件失败后测试多个条件。if/else 语句按顺序执行 else/if 语句,直到最终执行 else 语句。
以下是要创建一个 else/if 语句的语法:
if (first condition) { //code that runs if first condition is met } else if (second condition) { //code that runs if second condition is met } else if (n condition) { //code that runs if n condition is met } else { //code that runs if none of the above conditions are met }
下面是一个 else/if 语句的例子,该语句评估一个人的 testScore equates to either an A, B, C, D, or F 等级。
int testScore = 74; if (testScore >= 90) { Console.WriteLine("A"); } else if (testScore >= 80) { Console.WriteLine("B"); } else if (testScore >= 70) { Console.WriteLine("C"); } else if (testScore >= 60) { Console.WriteLine("D"); } else { Console.WriteLine("F"); }
switch 语句类似于前面的语句链,通过检查值而不是条件来匹配一系列情况。如果没有找到匹配的情况,则执行默认情况。
以下是要创建一个 switch 语句的语法:
switch (value) { case case1: //code to execute [break;] case case2: //code to execute [break;] default: //code to execute [break;] }
下面是一个 switch 语句的例子,该语句输出提供的 season 值对应的季节。
int season = 3; switch (season) { case 1: Console.WriteLine("Spring"); break; case 2: Console.WriteLine("Summer"); break; case 3: Console.WriteLine("Autumn"); break; case 4: Console.WriteLine("Winter"); break; }
我们已经确定了以下资源,以提供有关本课内容的更多背景和学习材料。我们鼓励您复习下面的材料并探索其他相关主题。
声明:
本文件灏天文库团队进行了翻译。尽管我们力求准确,但请注意,翻译可能包含错误或不准确之处。原文档以其原始语言为准。我们不对因使用此翻译而产生的任何误解或误译负责。