首页| 教育资讯| 留学| 校园| 作文| 范文| 论文| 教案| 课件| 试题| 专题| 教学反思| 网站地图

当前位置: 首页 > 资讯 > 利用switch语句实现多分支选择结构

利用switch语句实现多分支选择结构

时间:2015-10-09 12:43     来源:无忧教育网    作者:森林狼   点击:次  

switch语句用来实现多分支选择结构
学生成绩分类
85分以上为’A’等
70~84分为’B’等
60~69分为’C’等
……
人口统计分类
    按年龄分为老、中、青、少、儿童
switch语句的一般形式:
switch(表达式)
{  case  常量表达式1 :语句1
    case  常量表达式2 :语句2
       ┇    ┇       ┇
    case  常量表达式n :语句n
    default     :  语句n+1
}
switch(grade)若grade的值为“A” 85~100
{
    case  ’A’: printf(”85~100\n”);
    case  ’B’: printf(”70~84\n”);
    case  ’C’: printf(”60~69\n”);
    case  ’D’: printf(”<60\n”);
    default  : printf(”error\n”);
}
85~100
70~84
60~69
<60
error

例4.6 写程序,判断某一年是否为闰年。
用变量leap代表是否闰年的信息
若闰年,令leap=1;非闰年,leap=0
最后判断leap是否为1(真),若是,则输出“闰年”信息
参见教材图4.11
4年一闰年,但公历年份是整百数的,必须是400的倍数的才是闰年,不是400的倍数的,虽然是100的倍数,也是平年,这就是通常所说的:四年一闰,百年不闰,四百年再闰。
#include <stdio.h>
void main()
{int year,leap;
  printf("enter year:"); 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");  
}
if(year%4!=0)  leap=0;
else if (year%100!=0)  leap=1;
else if(year%400!=0)   leap=0;
else   leap=1;
if((year%4==0 && year%100!=0) 
                         || (year%400==0))
     leap=1;
else    leap=0;
enter year: 2100↙
2100 is not a leap year.

例4.6  运输公司对用户计算运费。运输距离越远,单位运费越低。
标准如下: 
                 s<250                没有折扣
       250≤s<500                 2%折扣
       500≤s<1000               5%折扣
      1000≤s<2000              8%折扣
      2000≤s<3000              10%折扣
      3000≤s                         15%折扣
设每吨每千米货物的基本运费为p,货物重为w,距离为s,折扣为d
总运费f的计算公式为f=p×w×s×(1-d)
折扣的变化规律(参见教材图4.12):
折扣的“变化点”都是250的倍数
在横轴上加一种坐标c,c的值为s/250
c代表250的倍数
当c<1时,表示s<250,无折扣
1≤c<2时,表示250≤s<500,折扣d=2%
2≤c<4时,d=5%;4≤c<8时,d=8%;
   8≤c<12时,d=10%;c≥12时,d=15%

#include <stdio.h>
void main()
   int c,s;
   double p,w,d,f;
   printf("请输入单价、重量和距离:");   
   scanf("%lf,%lf,%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(”运费:%10.2f元\n”,f); 
}
请输入单价、重量和距离:15,145.6,346.9↙
运费: 740550.72元
 
 
利用switch语句实现多分支选择结构更多精彩请点击无忧教育网http://www.edu399.com/


上一篇:儿行千里母担忧,一封家书寄思情


下一篇:嫌父母管教过严,孪生姐妹三次策划毒死父母

本文地址:http://www.edu399.com/jyzx/142219.html

本文标题:利用switch语句实现多分支选择结构

评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)