C语言及程序设计初步例程-25 用switch语句实现多分支结构

贺老师教学链接  C语言及程序设计初步 本课讲解


例:这是星期几?

#include 
int main()
{
    int week;
    scanf("%d", &week);
    switch(week)
    {
    case 0:
        printf("Sunday\n");
    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");
    default :
        printf("error\n");
    }
    return 0;
}

必要时,用break及时退出
#include 
int main()
{
    int week;
    scanf("%d", &week);
    switch(week)
    {
    case 0:
        printf("Sunday\n"); break;
    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;
    default :
        printf("error\n");
    }
    return 0;
}

多个case可以共用一组执行语句
#include 
int main()
{
    int week;
    scanf("%d", &week);
    switch(week)
    {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        printf("Workday\n"); break;
    case 0:
    case 6:
        printf("Weekend\n"); break;
    default :
        printf("error\n");
    }
    return 0;
}

简单的四则“运算器”
#include 
int main()
{
    float a,b;
    char c;
    printf("Please enter a,b and op:");
    scanf("%f%c%f",&a,&c,&b);
    switch(c)
    {
    case '+':
        printf("%f+%f=%f\n",a,b,a+b);
        break;
    case '-':
        printf("%f-%f=%f\n",a,b,a-b);
        break;
    case '*':
        printf("%f*%f=%f\n",a,b,a*b);
        break;
    case '/':
        if(b!=0.0) /*分母不能等于0*/
            printf("%f/%f=%f\n",a,b,a/b);
        else
            printf("error!\n");
        break;
    default:
        printf("error!\n");
        break;
    }
    return 0;
}


你可能感兴趣的:(C语言及程序设计初步例程-25 用switch语句实现多分支结构)