第三章分支结构
分支结构主要有if-else语句的嵌套、else-if语句、switch语句。
利用if-else语句计算居民水费
认识字符型数据
1)、在scanf()函数中用%c输入。
2)、ASCII字符集:每个字符都有唯一的次序值,即ASCII码。
3)、区分:1是整型数据,'1’是字符。
4)、字符也可用ch=getchar(),putchar()输入输出,注意它们都只能输入输出一个字符。
逻辑运算
逻辑运算符
运算符 | 名称 |
---|---|
! | 非 |
&& | 与 |
|| 或
逻辑运算符&&和||的优先级低于关系运算符,故
(ch>=‘a’)&&(ch<=‘z’)
等价于
ch>=‘a’&&ch<=‘z’
运用逻辑运算输出闰年
getchar()的作用
在统计字符的程序中
scanf("%d",&n);//nwie字符总数
getchar();//读入并舍弃换行符
应该是scanf()函数自带换行符,会影响字符统计。getchar()具有读入并删除换行符的功能。
switch语句
/*书中查询自动售货机中的商品价格*/
#include <stdio.h>
int main()
{
int choice,i;
double price;
/*显示菜单*/
printf("[1]select crisps\n");
printf("[2]select popcorn\n");
printf("[3]select chocolate\n");
printf("[4]select cola\n");
printf("[0]exit\n");
for(i=1;i<=5;i++){
printf("enter choice:");
scanf("%d",&choice);//输入表达式的值
if(choice==0)
break;//用break跳出for循环
switch(choice){
case 1:price=3.0;break;//'1'为常量表达式
case 2:price=2.5;break;
case 3:price=4.0;break;
case 4:price=3.5;break;
default:price=0.0;break;//switch语句的形式
}
printf("price=%0.1f\n",price);
}//for循环结束
return 0}
执行流程(虚线内表示没有break的情况)
1)、在switch语句中,表达式和常量表达式的值一般是整型或字符型,所有的常量表达式的值都不能相等。每个语句段可以包括一条或多条语句,也可以为空语句。
2)、default可以省略,但省略了default,当表达式的值于任何一个常量表达式的值都不相等,就什么都不执行。
3)、在没有使用break的switch语句中,“case 常量表达式”和“default”的作用相当于语句标号。当表达式的值与之相匹配时,不但执行相应的语句段,还按顺序执行后面的所有语句段。
(所以说没有break的结果会是用户输入选择后会输出用户不需要的讯息)
完成一下习题
/*收费*/
#include <stdio.h>
int main(){
int fee,y1,y2,time;
//y1 y2分别为里程收费和停顿时间收费
double l;//里程
printf("enter l:");
scanf("%lf",&l);
printf("enter time:");
scanf("%\d",&time);
if(l<=3){
y1=3;
}else if(l<=10){
y1=(l-3)*2+3;
}else{
y1=(l-10)*3+24;
}
int a;//收费次数
if(a=time/5.0){
y2=2*a;
}
fee=y1+y2;
printf("fee=%d元",fee);
return 0;
}
//判断是否为三角形
#include <stdio.h>
#include <math.h>
int main(){
double x1,x2,x3,y1,y2,y3;//三点的坐标
double a,b,c,s;//三边长
double area;//面积
printf("enter A:");scanf("%lf%lf",&x1,&y1);
printf("enter B:");scanf("%lf%lf",&x2,&y2);
printf("enter C:");scanf("%lf%lf",&x3,&y3);
a=sqrt(pow(x1-x2,2)+pow(y1-y2,2));
b=sqrt(pow(x1-x3,2)+pow(y1-y3,2));
c=sqrt(pow(x2-x3,2)+pow(y2-y3,2));
s=(a+b+c)/2;
if((a+b>c)||(a+c>b)||(b+c>a)){
area=sqrt(s*(s-a)*(s-b)*(s-c));
printf("三角形面积%.2f",area);
} else{
printf("imppossible");
}
return 0;
}
嵌套的if-else语句
else和if的匹配准则:else和与它最靠近的没有与别的else匹配的if相匹配。