实验四 逻辑运算和判断选取控制

u    实验目的

1、掌握关系运算符和逻辑运算符

2、掌握 if 语句

3、掌握 switch 语句

4、掌握选择结构程序设计

u    预习内容

见教材第五章

u    实验重点

1、学会正确使用逻辑运算符和逻辑表达式。

2、熟练掌握if语句和switch语句。

u    实验难点

1、熟练掌握if语句和switch语句。

2、学习调试程序。

u    实验内容

编写并运行3个有代表性的程序:

1、求一分段函数的输出值,在程序运行当中动态输入x的值,根据x的之所在范围决定输出值。

2、输入一个百分制成绩,要求输出成绩等级ABCDE,联系使用switch语句。

3、输入4个整数,按由小到大顺序输出。

u    参考例题

【例】求一元二次方程ax*x+b*x+c=0的解a0
/*功能求一元二次方程的解。*/
#include  "math.h"
main()
{float a,b,c,disc,x1,x2,p,q;
  scanf(“%f,%f,%f”, &a, &b, &c);

 if (fabs(a)<=1e-6)       /*fabs():求绝对值库函数*/
   printf(“is not a quadratic”);

else

{

disc=b*b-4*a*c;

   if (fabs(disc)<=1e-6)       
       printf(“x1=x2=%7.2f\n”, -b/(2*a));  /*
输出两个相等的实根*/
  else

if (disc>1e-6)
           {x1=(-b+sqrt(disc))/(2*a);     /*
求出两个不相等的实根*/
             x2=(-b-sqrt(disc))/(2*a);
             printf("x1=%7.2f,x2=%7.2f\n", x1, x2);
           }
else
     {p=-b/(2*a);                /*
求出两个共轭复根*/
      q=sqrt(fabs(disc))/(2*a);
      printf(“x1=%7.2f + %7.2f i\n“, p, q);    /*
输出两个共轭复根*/
       printf(”x2=%7.2f - %7.2f i\n“, p, q);
      }
   }

}

【例】 写程序,判断某一年是否为闰年。

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);

}

公告通知
教学日历
疑难留言
同学你好!对本课程有哪些建议?