引言
在C语言中,switch语句是一种选择结构,它允许根据变量的值来执行不同的代码块。 下面是一些包含switch语句的C代码示例,这些示例展示了如何使用switch来处理不同的情况。
基础示例
c include
int main() { int day_of_week;
// 假设用户输入一个数字来表示一周中的某一天 printf("Enter the number of the day of the week (0-6): "); scanf("%d", &day_of_week);
switch (day_of_week) { case 0: printf("It's Sunday.\n"); break; case 1: printf("It's Monday.\n"); break; case 2: printf("It's Tuesday.\n"); break; case 3: printf("It's Wednesday.\n"); break; case 4: printf("It's Thursday.\n"); break; case 5: printf("It's Friday.\n"); break; case 6: printf("It's Saturday.\n"); break; default: printf("Invalid day of the week.\n"); }
return 0; }
使用标签跳转
在某些情况下,你可能需要在不匹配的情况下立即退出switch语句。 这可以通过使用break语句实现,或者在switch之后直接返回,如下所示:
c include
int main() { int number;
printf("Enter a number (0-5): "); scanf("%d", &number);
switch (number) { case 0: case 1: case 2: case 3: case 4: case 5: printf("The number is between 0 and 5.\n"); break; default: printf("The number is not between 0 and 5.\n"); }
return 0; }
嵌套switch
switch语句也可以嵌套在其他switch语句中,以便处理更复杂的情况。 以下是一个嵌套switch的示例:
c include
int main() { int month, day;
printf("Enter the month (1-12): "); scanf("%d", &month); printf("Enter the day (1-31): "); scanf("%d", &day);
switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: if (day < 1 || day > 31) { printf("Invalid day for this month.\n"); } else { printf("The date is valid.\n"); } break; case 4: case 6: case 9: case 11: if (day < 1 || day > 30) { printf("Invalid day for this month.\n"); } else { printf("The date is valid.\n"); } break; case 2: // Check for leap year if ((day < 1 || day > 29) || ((day == 29) && !(2000 <= year % 400 || (year % 4 == 0 && year % 100 != 0)))) { printf("Invalid day for this month.\n"); } else { printf("The date is valid.\n"); } break; default: printf("Invalid month.\n"); }
return 0; }
在这个例子中,我们首先检查月份是否有效,然后根据月份检查日期是否有效。 如果月份是2月,我们还需要检查是否为闰年。