实验四 逻辑运算和判断选取控制 |
u 实验目的1、掌握关系运算符和逻辑运算符 2、掌握 if 语句 3、掌握 switch 语句 4、掌握选择结构程序设计 u 预习内容 见教材第五章 u 实验重点 1、学会正确使用逻辑运算符和逻辑表达式。 2、熟练掌握if语句和switch语句。 u 实验难点 1、熟练掌握if语句和switch语句。 2、学习调试程序。 u 实验内容 编写并运行3个有代表性的程序: 1、求一分段函数的输出值,在程序运行当中动态输入x的值,根据x的之所在范围决定输出值。 2、输入一个百分制成绩,要求输出成绩等级A、B、C、D、E,联系使用switch语句。 3、输入4个整数,按由小到大顺序输出。 u 参考例题 【例】求一元二次方程ax*x+b*x+c=0的解(a≠0)。 if (fabs(a)<=1e-6) /*fabs():求绝对值库函数*/ else { disc=b*b-4*a*c; if (fabs(disc)<=1e-6) if (disc>1e-6) } 【例】 写程序,判断某一年是否为闰年。 main() { int year,leap; scanf(“%d”,&year); if(year%4==0) { if(year%100==0) { if(year%400==0) leap=1; else leap=0; } else leap=1; } else leap=0; if(leap) printf(“%d is ”,year); else printf(“%d is not ”,year); printf(“a leap year.\n”);
} 【例】 运输公司对用户计算运费。 main() { int c,s; float p,w,d,f; scanf(“%f,%f,%d”,&p,&w,&s); if(s>=3000) c=12; else c=s/250; switch(c) { case 0:d=0; break; case 1:d=2; break; case 2: case 3:d=5; break; case 4: case 5: case 6: case 7:d=8; break; case 8: case 9: case 10: case 11:d=10; break; case 12:d=15; break; } f=p*w*s*(1-d/100.0); printf(“freight=%15.4f”,f); } |
|