文档介绍:1 The C Programming Language Chapter 5 Control Flow 第4章选择结构程序设计?选择结构的作用是根据给定的条件来决定做什么的操作。? if语句? if-else 语句? if-else if-else 语句 2 The C Programming Language Chapter 5 Control Flow if 语句的形式?单 if语句?其一般形式为: ? if ( 表达式) 语句表达式语句假真系统首先对表达式求解,当结果为“真”(非 0)时,则执行指定的语句;否则跳过指定语句,接着执行 if语句的下一语句。 if 语句 3 The C Programming Language Chapter 5 Control Flow 求两个整数中较大者。分析: 可设三个变量 a,b, max 。首先假设 max=a ,然后判断 max 和b,若 max<b ,则 max=b ,最后输出 max 。#include " " void main() { int a,b,max ; printf ("请输入 a,b 的值\n"); scanf("%d,%d",&a,&b ); max=a; if(max <b) max=b; printf("max =% d",max ); } 4 The C Programming Language Chapter 5 Control Flow ? if-else 语句?其一般形式为: if ( 表达式) 语句 1 else 语句 2 表达式语句 1 假真语句 2 系统先对表达式求解,当结果为“真”(非 0)时,执行语句 1; 当结果为“假”(0)时,执行语句 2。 5 The C Programming Language Chapter 5 Control Flow 利用 if-else 语句编写程序,求两个整数中较大者。#include " " void main() { int a,b ; printf("a,b ="); scanf("%d,%d",&a,&b ); if (a>b) printf("max =% d\n",a ); else printf("max =% d\n",b ); } 6 The C Programming Language Chapter 5 Control Flow ? if-else if-else 语句?其一般形式为: if ( 表达式 1)语句 1 else if ( 表达式 2) 语句 2 else if ( 表达式 3) 语句 3…… else if ( 表达式 n-1) 语句 n-1 else 语句 n 假真表达式 n-1 表达式 1 假真表达式 2假真假真……语句 1语句 2语句 3语句 n-1 语句 n 表达式 3 系统首先求解表达式 1的值,当其值为“真”(非 0)时,执行语句 1,然后跳出该选择结构;否则求解表达式 2的值,当其值为“真”(非 0)时,则执行语句 2, 然后跳出该选择结构;否则再继续求解表达式 3,当其值为“真”(非 0)时, 执行语句 3,然后跳出该选择结构;否则接着进行判断,依次类推。如果经过求解,所有的表达式都为“假”(0),就执行最后一个 else 部分的语句 n,从而结束整个 if语句。 7 The C Programming Language Chapter 5 Control Flow 给出百分制的成绩,要求输出成绩等级 A、B、C、D、E。 90分以上为 A,80~89分为 B,70~79分为 C,60~69分为 D ,60分以下为 E。分析: 设成绩为 score ,假设取值在 0~100 之间,没有错误的输入,则有: 0≤ score <60 E 60≤ score ≤69 D 70≤ score ≤79 C 80≤ score ≤89 B 90≤ score ≤ 100 A #include " " void main() { int score; printf ("请输入学生的成绩\n"); scanf("%d",&score ); if(score >=0&&score<60) printf("grade is E\n");