#include <stdio.h> int main(){ int a; printf("Input integer number:"); scanf("%d",&a); if(a==1){ printf("Monday\n"); }else if(a==2){ printf("Tuesday\n"); }else if(a==3){ printf("Wednesday\n"); }else if(a==4){ printf("Thursday\n"); }else if(a==5){ printf("Friday\n"); }else if(a==6){ printf("Saturday\n"); }else if(a==7){ printf("Sunday\n"); }else{ printf("error\n"); } return 0; }運行結果:
#include <stdio.h> int main(){ int a; printf("Input integer number:"); scanf("%d",&a); switch(a){ case 1: printf("Monday\n"); break; case 2: printf("Tuesday\n"); break; case 3: printf("Wednesday\n"); break; case 4: printf("Thursday\n"); break; case 5: printf("Friday\n"); break; case 6: printf("Saturday\n"); break; case 7: printf("Sunday\n"); break; default:printf("error\n"); break; } return 0; }運行結果:
switch(表達式){
case 整型數值1: 語句 1;
case 整型數值2: 語句 2;
......
case 整型數值n: 語句 n;
default: 語句 n+1;
}
#include <stdio.h> int main(){ int a; printf("Input integer number:"); scanf("%d",&a); switch(a){ case 1: printf("Monday\n"); case 2: printf("Tuesday\n"); case 3: printf("Wednesday\n"); case 4: printf("Thursday\n"); case 5: printf("Friday\n"); case 6: printf("Saturday\n"); case 7: printf("Sunday\n"); default:printf("error\n"); } return 0; }運行結果:
break;
語句。#include <stdio.h> int main(){ int a; printf("Input integer number:"); scanf("%d",&a); switch(a){ case 1: printf("Monday\n"); break; case 2: printf("Tuesday\n"); break; case 3: printf("Wednesday\n"); break; case 4: printf("Thursday\n"); break; case 5: printf("Friday\n"); break; case 6: printf("Saturday\n"); break; case 7: printf("Sunday\n"); break; default:printf("error\n"); break; } return 0; }運行結果:
break;
語句。case 10: printf("..."); break; //正確 case 8+9: printf("..."); break; //正確 case 'A': printf("..."); break; //正確,字符和整數可以相互轉換 case 'A'+19: printf("..."); break; //正確,字符和整數可以相互轉換 case 9.5: printf("..."); break; //錯誤,不能為小數 case a: printf("..."); break; //錯誤,不能包含變量 case a+10: printf("..."); break; //錯誤,不能包含變量