第四章 选择结构程序设计"/>
第四章 选择结构程序设计
C语言有两种选择语句:(1)if语句,实现两个分支的选择结构;
(2)Switch语句,实现多分支的选择结构。
1.求ax^2+bx+c=0方程的解。
#include<stdio.h>
#include<math.h>
int main(){double a,b,c,disc,x1,x2,realpart,imagpart;scanf("%lf,%lf,%lf",&a,&b,&c);printf("The equation");if(fabs(a)<=1e-6)printf("is not a quadractic\n");else{disc=b*b-4*a*c;if(fabs(disc)<=1e-6)printf("has two equal roots:%8.4f\n",-b/));elseif(disc>1e-6){x1=(-b+sqrt(disc))/(2*a);x2=(-b-sqrt(disc))/(2*a);printf("has distinct real roots:%8.4fand %8.4f\n",x1,x2); } else{realpart=-b/(2*a);imagpart=sqrt(-disc)/(2*a);printf("has complex roots:\n");printf("%8.4f+%8.4fi\n",realpart,imagpart);printf("%8.4f-%8.4fi\n",realpart,imagpart); } }return 0;
}
2.求一个一元二次方程组的解:
#include<stdio.h>
#include<math.h>
int main(void){double a,b,c,d;printf("请输入一元二次方程的三个系数:");scanf("%lf%lf%lf",&a,&b,&c);if(fabs(a-0)<=1e-6){printf("输入有误,程序结束运行\n");return 0; }d=b*b-4*a*c;if(d<0)printf("此方程无实数根\n");else if(fabs(d)<=1e-6)printf("此方程的根为%lf\n",-b/(2*a));elseprintf("此方程的两个根为%lf,%lf\n",(-b+sqrt(d))/(2*a),(-b+sqrt(d))/(2*a));return 0;
}
3.switch语句:电梯程序:
break:结束一个Switch语句的运行。
#include<stdio.h>
int main(void){printf("请输入所要到达的楼层:");int a;scanf("%d",&a);switch(a){default:printf("没有这个楼层\n");break;case1:printf("上一楼\n");break;case2:printf("上二楼\n");break;case3:printf("上三楼\n");break; }return 0;
}
4.Switch语句:电梯程序:
break:结束一个电梯程序的运行。
#include<stdio.h>
int main(void){printf("请选择要到达的楼层:");int a;scanf("%d",&a);switch(a){default:printf("没有这个楼层\n");break;case1:printf("上一楼\n");break;case2:printf("上二楼\n");break;case3:printf("上三楼\n"); break; }return 0;
}
5.大写字母加上32=对应小写字母
#include<stdio.h>
#define DAXIE 1
void f1(void);
void f2(void);
void f3(void);
int main(void)
{f3();return 0;
}
void f1(void){char ch;while((ch=getchar())!='\n'){#if 1if(ch>='A'&&ch<='Z')ch+=32;#elseif(ch>='a'&&ch<='z')ch-=32;#endifputchar(ch); }
}
void f2(void){char ch;while((ch=getchar())!='\n'){#if 1if(ch>='A'&&ch<='Z')ch+=32;#elseif(ch>='a'&&ch<='z')ch-=32;#endifputchar(ch); }
}
void f3(void){char ch;while((ch=getchar())!='\n'){#if 1if(ch>='A'&&ch<='Z')ch+=32;#elseif(ch>='a'&&ch<='z')ch-=32;#endifputchar(ch); }
}
重难点提要:
1.三种循环结构:
for(); while(); do-while()三种
for循环当中必须是两个分号
do-while循环至少执行一次循环
2.break和continue的差别
break:看到break跳出整个一层循环
continue:结束本次循环,循环体内剩下的语句不再执行,跳到循环开始,判断循环条件,进行新一轮的循环。
3.嵌套循环
循环里面有循环
4.取余的注意(负数取余)
#include<stdio.h>
int main(){int a=-10,b=-6;printf("%d",a%b);return 0;
} //结果是-4
5.case可以嵌套写,表示多个条件一个操作
case1:case2:case3:printf("11111");
更多推荐
第四章 选择结构程序设计
发布评论