第3章分支结构
第3章 分支结构
分支结构一求分段函数 *[例2-4]居民用水*/ #include <stdio.h> y= 4x x≤15 3 void main ( 2.5x-10.5x>15 { double x,y; printf("Enter x(x>=O)n");/*输入提示*/ scanf("%lf",&x); k调用scanfi函数输入数据* if(x<=15) /*if-else语句,关系表达式X<=15*/ y=4*X/3; else 根据条件选择所要执行的语 y=2.5*x-10.5; 句 printf("y f(%f)=%.2f\n",x,y);
分支结构-求分段函数 /*[例2-4] 居民用水*/ #include <stdio.h> void main ( ) { double x, y; printf("Enter x (x>=0):\n"); /* 输入提示 */ scanf("%lf", &x); /* 调用scanf函数输入数据 */ if (x <= 15) /* if-else语句,关系表达式 x<=15 */ y = 4 * x / 3; else y = 2.5 * x - 10.5; printf("y = f(%f) = %.2f\n", x, y); } 4 15 ( ) 3 2.5 10.5 15 x x y f x x x = = − 根据条件选择所要执行的语 句
第3章分支结构 3.1统计输入的一批字符中各类字符的数量 3.2查询自动售货机中商品的价格 3.3分支结构程序设计
第3章 分支结构 3.1 统计输入的一批字符中各类字符的数量 3.2 查询自动售货机中商品的价格 3.3 分支结构程序设计
3.1统计输入的一批字符中各类字符的数量 例3-1输入10个字符, 统计其中英文字母、数 字字符和其他字符的个数。 3.1.1程序解析 3.1.2字符类型 3.1.3字符数据的输入和输出 3.1.4逻辑运算 3.1.5else-if语句
3.1 统计输入的一批字符中各类字符的数量 例3-1 输入10个字符,统计其中英文字母、数 字字符和其他字符的个数。 3.1.1 程序解析 3.1.2 字符类型 3.1.3 字符数据的输入和输出 3.1.4 逻辑运算 3.1.5 else-if 语句
3.1.1程序解析-[例3-1] c"℃:lC-language\2010 Ckjltscx.… #include <stdio.h> 请输入10个字符:123hyt5/& letter=3,digit=3,other=4 void main() Press any key to continue int digit,i,letter,other; char ch; digit letter other 0; *三个累加器初始化*/ printf(请输入10个字符:"); 多层缩进的书写格式 fori=1;i<=10;i++) 使程序层次分明 ch getchar(); *从键盘输入一个字符,赋值给变量ch*/ if(ch>='a'&&ch<='z')‖(ch>='A'&&ch<='Z) letter ++ /*ch是英文字母,累加letter*/ else if(ch >='0'&&ch <='9') digit ++ *ch是数字字符,累加digit*/ else other ++ 体ch是其他字符,累加other*/ printf("letter=%d,digit=%d,other=%d\n",letter,digit,other);
3.1.1 程序解析-[例3-1] #include <stdio.h> void main ( ) { int digit, i, letter, other; char ch; digit = letter = other = 0; /*三个累加器初始化*/ printf(“请输入10个字符: "); for(i = 1; i <= 10; i++) { ch = getchar( ); /* 从键盘输入一个字符,赋值给变量 ch */ if((ch >= 'a' && ch <= 'z' ) || ( ch >= 'A' && ch <= 'Z')) letter ++; /* ch是英文字母,累加letter */ else if(ch >= '0' && ch <= '9') digit ++; /* ch是数字字符,累加digit */ else other ++; /* ch是其他字符 , 累加other */ } printf("letter=%d,digit=%d,other=%d\n",letter,digit,other); } 多层缩进的书写格式 使程序层次分明