决策语句要求程序员指定一个或多个要由程序评估或测试的条件,以及确定条件为真时要执行的一个或多个语句,如果条件确定则可以选择要执行的其他语句确定为假。
以下是决策声明的类型-
序号 | 声明与说明 |
---|---|
1 | if语句 if语句由一个布尔表达式和一个或多个语句组成。 |
2 | if ... else语句 if语句后可以跟可选的else语句,该语句在布尔表达式为false时执行。 |
3 | 嵌套的if语句 您可以在另一个if or else if语句中使用一个if or else if语句。 |
4 | switch语句 switch语句允许针对值列表测试变量是否相等。 |
5 | 嵌套的switch语句 可以在另一个switch语句中使用一个switch语句。 |
让我们看一下C#中if-else决策语句的示例。
using System; namespace Demo { class Program { static void Main(string[] args) { int a = 50; if (a < 10) { Console.WriteLine("a is less than 10"); } else { Console.WriteLine("a is not less than 10"); } Console.WriteLine("a = {0}", a); Console.ReadLine(); } } }
输出结果
a is not less than 10 a = 50