第25节 switch语句多分支结构

一.swithch语句实例

#include <stdio.h>
int main()
{
	int week;
	scanf_s("%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("Thurday\n");
		case 5:
			printf("Friday\n");
		case 6:
			printf("Saturday\n");
		default:
			printf("error\n");
	}
	return 0;
}
运行结果:
3
Wednesday
Thurday
Friday
Saturday
error

二.用break语句跳出switch结构

#include <stdio.h>
int main()
{
	int week;
	scanf_s("%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("Thurday\n"); break;
		case 5:
			printf("Friday\n"); break;
		case 6:
			printf("Saturday\n"); break;
		default:
			printf("error\n");
	}
	return 0;
}
运行结果:
3
Wednesday

三.break的灵活运用

#include <stdio.h>
int main()
{
	int week;
	scanf_s("%d", &week);
	switch (week) 
	{
		
		case 1:
		case 2:
		case 3:
		case 4:
		case 5:
			printf("workday\n"); break;
		case 6:
		case 0:
			printf("Weekend\n"); break;
		default:
			printf("error\n");
	}
	return 0;
}

四.简单的四则"运算器"

#include <stdio.h>
int main()
{
	double a, b;
	char c;
	printf("按以下一种格式输入\na+b\na-b\na*b\na/b\n");
	scanf_s("%lf%c%lf", &a, &c, 1, &b);
	switch (c)
	{
	case'+':
		printf("%g+%g=%g\n", a,b,a + b); break;
	case'-':
		printf("%g-%g=%g\n", a, b, a - b); break;
	case'*':
		printf("%g*%g=%g\n", a, b, a * b); break;
	case'/':
		if (b != 0) //分母不能等于0;
			printf("%g/%g=%g\n", a, b, a / b);
		else
			printf("error!\n");
		break;
	default:
		printf("error!\n");
		break;
	}
}

五.程序阅读

#include <stdio.h>
int main()
{
    int i = 10, j, m = 0, n = 0;
    j = i % 3;
    switch (j)
    {
    case 0:
        m++;
        break;
    case 1:
    case 2:
        n++;
        break;
    default:
        printf("i=%d\n", i);
    }
    printf("m=%d, n=%d\n", m, n);
    return 0;
}
运行结果:
m=0, n=1
#include <stdio.h>
int main()
{
    int a = 2, b = 7, c = 5;
    switch (a > 0)  //a>0,取其值,然后决定与哪个分支匹配
    {
    case 1:
        switch (b < 0)
        {
        case 1:
            printf("@");
            break;
        case 2:
            printf("!");
            break;
        }
    case 0:
        switch (c == 5)
        {
        case 1:
            printf("*");
            break;
        case 2:
            printf("#");
            break;
        default:
            printf("#");
            break;
        }
    default:
        printf("&");
    }
    printf("\n");
    return 0;
}
运行结果:
*&
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值