1. 多重IF结构
如果IF条件需要分成多种情况时,将要用到多重IF条件的用法,即else –if结构,这的语法如下:
If(条件1)
{
语句块1;
}
Else if(条件2)
{
语句块2;
}
….
Else if(条件n)
{
语句块n;
}
[else
{
语句块n+1;
}
上面的结构就是把IF条件分成了n种情况进行判断,符合某种条件则执行下面的代码。例如,如果满足条件1,就执行语句块1;如果条件满足条件2,则执行语句2下的代码,依次判断。如果条件均不满足以上n种情况,那么就执行else那么部分的代码块(else语句块是可选择的)。
下面来看个简单的例子。
using System;
using System.Collections.Generic;
using System.Text;
namespace AddApp
{
class ElseIfDemo
{
public static void Main()
{
int month;
Console.WriteLine("请输入某一个月份(1-12):");
month=int.Parse(Console.ReadLine();
if(month<1)
{
Console.WriteLine("您输入的月份不正确!");
}
else if(month<=3)
{
Console.WriteLine("您输入的月份属于第1个季度");
}
else if(month<=6)
{
Console.WriteLine("您输入的月份属于第2个季度");
}
else if(month<=9)
{
Console.WriteLine("您输入的月份属于第3个季度");
}
else if(month<=12)
{
Console.WriteLine("您输入的月份属于第4个季度");
}
else
{
Console.WriteLine("您输入的月份不正确!");
}
}
}
}
在这个示例中使用else if结构判断用户输入的月份属于哪个季度,最后显示判断结果。如果用户输入的月份不正确(大于12或小于1),会显示错误信息。
2.嵌套IF结构
当需要检查多个条件时,应使用嵌套if结构,语示如下所示:
if (条件1)
{
if(条件2)
{
语句块1;
}
}
[else]
{
if(条件3)
{
语句块2;
}
else
{
语句块3;
}
}]
当条件1的计算值为true时,检查条件2,条件2的计算结果为true时,执行语句块1。而如果条件1的计算结果为false时,检查条件3;条件3的计算值为true时,执行语句块2,否则执行语句块3.
下面来看个简单的例子:
using System;
using System.Collections.Generic;
using System.Text;
namespace AddApp
{
class Program
{
static void Main(string[] args)
{
char ch;
float score;
Console.WriteLine("请输入学生成绩");
score = float.Parse(Console.ReadLine());
if ((score < 0) || (score > 100))
{
Console.WriteLine("你输入的分数不对");
Console.ReadLine();
}
else
{
if (score >= 60)
{
if (score >= 70)
{
if (score >= 80)
{
if (score >= 90)
{
Console.WriteLine("90分以上");
Console.ReadLine();
}
else
{
Console.WriteLine("80--90");
Console.ReadLine();
}
}
else
{
Console.WriteLine("70--80");
Console.ReadLine();
}
}
else
{
Console.WriteLine("60--70");
Console.ReadLine();
}
}
else
{
Console.WriteLine("不及格");
Console.ReadLine();
}
}
}
}
}
上述例子用来对用户输入的分数时行判断它所在那个分数段内。例如,如果用户输入75,那就会输出70-80.
3.总结
不管使用什么样的方式进行判断,就是要看你对条件的运用了。当条件之间有分支的时候,就用多重if语句,那条件之间有递进关系的时候,就用嵌套if语句。