在 C# 编程中,if 语句用于测试条件。C# 中有多种类型的 if 语句。
if 语句
if-else 语句
嵌套 if 语句
if-else-if 阶梯
C# if 语句测试条件。如果条件为真则执行。
if(condition){ //要执行的代码 }
using System; public class IfExample { public static void Main(string[] args) { int num = 10; if (num % 2 == 0) { Console.WriteLine("是偶数"); } } }
输出:
是偶数
C# if-else 语句也测试条件。如果条件为真则执行if 块,否则执行else 块。
if(condition){ //如果条件为真,代码 }else{ //如果条件为假,代码 }
using System; public class IfExample { public static void Main(string[] args) { int num = 11; if (num % 2 == 0) { Console.WriteLine("是偶数"); } else { Console.WriteLine("奇数"); } } }
输出:
是奇数
在此示例中,我们使用Console.ReadLine()方法从用户那里获取输入。它返回字符串。对于数值,您需要使用Convert.ToInt32()方法将其转换为 int。
using System; public class IfExample { public static void Main(string[] args) { Console.WriteLine("请输入一个数字:"); int num = Convert.ToInt32(Console.ReadLine()); if (num % 2 == 0) { Console.WriteLine("是偶数"); } else { Console.WriteLine("奇数"); } } }
输出:
输入数字:11是奇数
输出:
输入一个数字:12是偶数
C# if-else-if 梯形语句从多个语句中执行一个条件。
if(条件1){ //条件1为真时执行的代码 }else if(条件2){ //条件2为真时执行的代码 } else if(条件3){ //条件3为真时执行的代码 } ... else{ //所有条件为假时执行的代码 }
using System; public class IfExample { public static void Main(string[] args) { Console.WriteLine("请输入数字查看成绩:"); int num = Convert.ToInt32(Console.ReadLine()); if (num <0 || num >100) { Console.WriteLine("号码错误"); } else if(num >= 0 && num < 50){ Console.WriteLine("失败"); } else if (num >= 50 && num < 60) { Console.WriteLine("D 级"); } else if (num >= 60 && num < 70) { Console.WriteLine("C 级"); } else if (num >= 70 && num < 80) { Console.WriteLine("B 级"); } else if (num >= 80 && num < 90) { Console.WriteLine("A 级"); } else if (num >= 90 && num <= 100) { Console.WriteLine("A+ 级"); } } }
输出:
输入数字以查看等级:66C级
输出:
输入一个数字以检查等级:-2错号码