程序设计基础 第5章分支控制结构
程序设计基础 第5章 分支控制结构
引入 需要根据不同条件选择处理的问题 ◆求一个数的绝对值(如果是负数,取反) ◆求两个数的最大值(比较两个数,取出较大值) ◆根据百分制分数,输出五级制成绩(>=90A·<60E) ■算法设计上用分支(选择)结构处理 程序实现上用if、if-else、if-else-if和switch语句 真(非0) (0) a>=b 假(0) max=a max=b (0)士 输出max值 猖 2129
2/29 引入 ◼ 需要根据不同条件选择处理的问题 ◆ 求一个数的绝对值(如果是负数,取反) ◆ 求两个数的最大值(比较两个数,取出较大值) ◆ 根据百分制分数,输出五级制成绩(>=90 A. <60 E) ◼ 算法设计上用分支(选择)结构处理 ◼ 程序实现上用if、if-else、if-else-if和switch语句 输出max值 真(非0) 假(0) a>=b max=a max=b 真(非0) 假(0) x<0 y = - x 输出y值 y = x
例5.1求给定整数的绝对值 #include<stdio.h> int main() { 假(0) x<0 int x,y; 真(非0) scanf("%/od"&x); Y=-x y=; if (x<0) 輸出y值 y=X对 printf("x=%od,|x|=%od",x,y); return O; 3129
3/29 #include<stdio.h> int main() { int x,y; scanf("%d",&x); y = x; if ( x < 0 ) y = -x; printf("x=%d,|x|=%d",x,y); return 0; } 例5.1 求给定整数的绝对值 真(非0) 假(0) x<0 y = - x 输出y值 y = x
例5.2输入两个整数,输出其中的大数 #include<stdio.h> int main() 真(非0 假(0) a>=b { int a,b,max; max=a max=b scanf("%/od%/od",&a,&b); if(a>=b) max a; 输出max值 else max b; printf("max=%od",max); return O; } 恩 4129
4/29 #include<stdio.h> int main() { int a,b,max; scanf("%d%d",&a,&b); if ( a >= b ) max = a; else max = b; printf("max=%d",max); return 0; } 例5.2 输入两个整数,输出其中的大数 输出max值 真(非0) 假(0) a>=b max=a max=b
例5.6输入百分制分数,输出五级成绩 #include<stido.h> 例:学生成绩分类: int main() A(>=90) B(8089) float score; scanf("O/of",&score); C(70~79) if score >=90) D(6069) printf("/04.1f is A.\n",score); E(K60) else if score >=80) 已知分数分类 printf("/04.1f is B.\n",score); else if(score >70) printf(04.1f is C.\n",score); else if(score>=60) printf("0/04.1f is D.\n",score); else printf(/04.1f is E.\n",score); return 0; } 猖 5/29
5/29 #include<stido.h> int main() { float score; scanf("%f",&score); if ( score >= 90 ) printf(“%4.1f is A.\n",score); else if ( score >= 80) printf(“%4.1f is B.\n",score); else if( score >= 70) printf(“%4.1f is C.\n",score); else if ( score >= 60 ) printf(“%4.1f is D.\n",score); else printf(“%4.1f is E.\n",score); return 0; } 例5.6 输入百分制分数,输出五级成绩 ◼ 例:学生成绩分类: A(>=90) B(80~89) C(70~79) D(60~69) E(<60) 已知分数 分类