一.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;
}
运行结果:
*&