switch(条件)//这里的条件只能是整型或字符型
{
case 1:
.....
break; //break是中断(跳出、结束)语句,如果没有break则语句会按照顺序执行下去
case 2:
......
break;
}
下面月份与天数计算的例子就是不使用break完成的
int y, m, d;
printf("输入年月日
");
cin >> y; cin >> m; cin >> d;
int x = 0;
switch (m - 1)//注意要月份减1
{
case 11:
x += 30;
case 10:
x += 31;
case 9:
x += 30;
case 8:
x += 31;
case 7:
x += 31;
case 6:
x += 30;
case 5:
x += 31;
case 4:
x += 30;
case 3:
x += 31;
case 2:
if ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0))
{//是闰年
x += 29;
}
else
{
x += 28;
}
case 1:
x += 31;
case 0:
break;
default:
printf("输入的月份有错");
break;
}
if (m == 1)
{
x = d - 1;
printf("至年初有%d天
", x);
}
else
{
x = x + d - 1;
printf("至年初有%d天
", x);
}
return 0;