一、if语句的格式
if语句有二种格式:
1、if 布尔表达式 then 语句;
2、if 布尔表达式 then 语句1
else 语句2;
当布尔表达式的值为真,则执行then后面的语句;值为假时有两种情况:要么什么也不做,要么执行else后面的语句。注意else前面没有分号,因为分号是两个语句间的分隔符号,而else并非语句。如果在该处画蛇添足加了分号,则编译时就会认为if语句到此结束,而把else当作另一语句的开头,输出语法错误的信息。
例1:输入两个整数,输出其中较大的数。
var
x,y:integer;
begin
readln(x,y);
if x>y then writeln(x);
if y>=x then writeln(y);
end.
思考:如果倒数第三行改成:if x>=y then writeln(x);会怎么样?
也可以用下用的代码表示:
var
x,y:integer;
begin
readln(x,y);
if x>y then writeln(x)
else writeln(y);
end.
例2:输入一个整数,判断它是奇数还是偶数。
var
a:integer;
begin
readln(a);
if a mod 2=0 then writeln(a,'-oushu')
else writeln(a,'-jishu');
end.
思考:如果采用odd函数程序应该怎么改?
例3:输入一个年份,判断它是不是闰年?
var
y:integer;
begin
readln(y);
if ((y mod 400=0) or ((y mod 4=0) and (y mod 100<>0))) then writeln(y,' is a leap year.')
else writeln(y,' is not a leap year.');
end.
二、if语句的嵌套
当需要求解的实际问题比较复杂,涉及到多个条件时,对于if语句的两种格式中的语句1和语句2同样允许是条件语句,称为条件语句的嵌套(或称为复合条件语句)。
嵌套的一般格式:
if 条件1
then
if 条件2
then 语句21
else 语句22
else
if 条件3
then 语句31
else 语句32;
在进行if语句的嵌套时应注意if与else的配对关系,请看下面的语句:
if 表达式1 then if 表达式2 then 语句1 else 语句2;
在此if语句中,else对应着哪一个if?,Pascal语法规定:else总是与最近一个if配对,故上句可以写成:
if 表达式1 then if 表达式2 then 语句1
else 语句2;
例4:输入三个正整数,输出其中最大的数。
var
a,b,c:integer;
begin
readln(a,b,c);
if a>b then if a>c then writeln(a)
else writeln(c)
else if b>c then writeln(b)
else writeln(c);
end.
也可以用下用的代码表示:
var
a,b,c,max:integer;
begin
readln(a,b,c);
max:=0;
if a>max then max:=a;
if b>max then max:=b;
if c>max then max:=c;
writeln(max);
end.
思考:上面的程序还能优化吗?
例5:输入某同学的数学百分制分成绩,输出成绩的等级A、B、C、D。规定90分以上为A;80-89分为B;60-79分为C;60分以下者为D。
var
s:integer;
begin
readln(s);
if s>=90 then writeln('A')
else if s>=80 then writeln('B')
else if s>=60 then writeln('C')
else writeln('D');
end.
三、作业
1、zerojudge:
基础题:a003、a799、d063、d064、d067、d071、d068
if语句的嵌套:d058、d065、a053
思考题:d050、d060、d066、d073、d277
2、输入两门课程的考试成绩,如果都及格就显示PASS,否则显示FAIL。
3、输入三个整数,按从小到大的顺序输出。
4、输入年、月,输出该月的天数。