当一个变量只有几种可能的取值时,则可以定义为枚举类型的变量。
一:枚举类型的输出
#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(" please input month name:"); scanf("%d",&m); switch(m){ case ill: printf("illegal month "); break; case Jan: printf("January "); break; case Feb: printf("February "); break; case Mar: printf("March "); break; case Apr: printf("April "); break; case May: printf("May"); break; case Jun: printf("June "); 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 "); } else if(used==Fortran){ printf("It is Fortran "); } else{ printf("It is C "); } printf("used=%d ",used); printf("Basic=%d Fortran=%d C=%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("请输入周日到周六的工作时间: "); //进行强制转换 (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; }