第三章 C语言程序控制结构(if、switch语句)
第三章 C语言程序控制结构if、switch语句 C程序的三种基本结构: 顺序结构 任务三 找出最高分和最低分 概 述 3.1 两个数据比较大小 问题: 输入两个整数,输出其中较大的数。 3.1 两个数据比较大小 3.1 两个数据比较大小 3.1 两个数据比较大小 用if语句构成分支结构,根据给定的条件进行判断,以决定执行某个分支程序段。 3.1 两个数据比较大小 3.1 两个数据比较大小 #include stdio.h main() { int a,b,max; printf(“\n input two int numbers:”) scanf(“%d%d”,a,b); /* 算法:找出a、b中较大的数,赋值给max */ printf(“max=%d”,max); getch(); } 3.1 两个数据比较大小 #include stdio.h main() { int a,b,max; printf(“\n input two int numbers:”) scanf(“%d%d”,a,b); max=a; if(maxb) max=b; printf(“max=%d”,max); } 课堂练习 写出以下程序运行的结果。 3.1 两个数据比较大小 3.1 两个数据比较大小 3.1 两个数据比较大小 3.1 两个数据比较大小 #include stdio.h main() { int a,b,max; printf(“\n input two int numbers:”) scanf(“%d%d”,a,b); /* 算法:找出a、b中较大的数,赋值给max */ printf(“max=%d”,max); getch(); } 3.1 两个数据比较大小 #include stdio.h main() { int a,b,max; printf(“\n input two int numbers:”) scanf(“%d%d”,a,b); if(ab) max=a; else max=b; printf(“max=%d”,max); getch(); } 3.1 两个数据比较大小 条件运算符 条件运算符: ? : (三目运算符) 一般形式:表达式1 ?表达式2 : 表达式3 条件运算符的值:如果表达式1的值为真,则取表达 式2的值,否取表达式3的值 3.1 两个数据比较大小 #include stdio.h main() { int a,b,max; printf(“\n input two int numbers:”) scanf(“%d%d”,a,b); max=(ab)?a:b; printf(“max=%d”,max); getch(); } 问题: 输入两个整数,输出其中较大的数。 3.2 三个数据中找最大值和最小值 3.2 三个数据中找最大值和最小值 1、if语句(第三种形式) #include stdio.h main() { int a,b,c,max,min; printf(“input 3 int numbers:\n”); scanf(“%d%d%d”,a,b,c); if(ab) {max=a;min=b;} else {max=b;min=a;} if(cmax)max=c; else if (cmin)min=c; printf(“max=%d,min=%d”,max,min); } 课堂练习 课堂练习 2、if语句使用注意事项 2、if语句使用注意事项 ②在三种形式的if语句中,在if关键字之后均为表达式。该表达式通常是逻辑表达式或关系表达式, 但也可以是其它表达式,如赋值表达式等,甚至也可以是一个变量。 3、if语句的嵌套 3、if语句的嵌套 if~else配对原则: 缺省{ }时,else总是和它上面离它最近的未配对的if配对。
原创力文档

文档评论(0)