c语言---枚举
当一个变量只有几种可能的取值时,则可以定义为枚举类型的变量。
一:枚举类型的输出
#include<stdio.h> enum month {ill,Jan,Feb,Mar,Apr,May,Jun }; int main(){ int i; enum month m; for(i=0;i<6;i++){ printf("\nplease input month name:"); scanf("%d",&m); switch(m){ case ill: printf("illegal month\n"); break; case Jan: printf("January\n"); break; case Feb: printf("February\n"); break; case Mar: printf("March\n"); break; case Apr: printf("April\n"); break; case May: printf("May"); break; case Jun: printf("June\n"); break; } } return 0; }
二:枚举元素的输出
#include<stdio.h> int main(){ enum language{Basic,Fortran,C }; enum language used; used=Fortran; if(used==Basic){ printf("It is Basic\n"); } else if(used==Fortran){ printf("It is Fortran\n"); } else{ printf("It is C\n"); } printf("used=%d\n",used); printf("Basic=%d\nFortran=%d\nC=%d",Basic,Fortran,C); return 0; }
实例:假定周一至周五每小时工资3元,每周六工资每小时4元,每周日工资每小时5元,输入一周每天的工作时数,计算周工资数。
#include<stdio.h> int main(){ enum weekday{sun,mon,tue,wed,thu,fri,sat }; enum weekday workday; int pay,hour,total; total=0; printf("请输入周日到周六的工作时间:\n"); //进行强制转换 (weekday)(workday+1) for(workday=sun;workday<=sat;workday=(weekday)(workday+1)){ scanf("%d",&hour); switch(workday){ case sun: pay = hour*5;break; case sat: pay = hour*4;break; default: pay = hour*3;break; } total+=pay; } printf("total pay is %d",total); return 0; }
非学无以广才,非志无以成学。
正是因为今天的不完美,才对未来充满希望。
----长帆