C#中的决策
决策结构要求程序员指定一个或多个要由程序评估或测试的条件,以及确定条件为真的情况下要执行的一条或多条语句,以及指定条件的情况下要执行的其他语句(可选)确定为假。
C#中的决策包括if语句,if-else语句,switch语句等。
让我们来看一个C#中if语句的例子。
示例
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
int x = 5;
//如果语句
if (x < 20) {
/* if condition is true then print the following */
Console.WriteLine("x is less than 20");
}
Console.WriteLine("value of x is : {0}", x);
Console.ReadLine();
}
}
}输出结果
x is less than 20 value of x is : 5
让我们看一下C#中if-else语句的示例。在这种情况下,如果第一个条件为假,则将检查else语句中的条件。
示例
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
int x = 100;
/* check the boolean condition */
if (x < 20) {
/* if condition is true then print the following */
Console.WriteLine("x is less than 20");
} else {
/* if condition is false then print the following */
Cohttp://tpcg.io/HoaKexnsole.WriteLine("x is not less than 20");
}
Console.WriteLine("value of a is : {0}", x);
Console.ReadLine();
}
}
}输出结果
x is not less than 20 value of a is : 100