#include <stdio.h>
#include <stdlib.h>
//平年2月28天,闰年2月29天
int day(int year,int month,int date)
{
int day=0;
int feb=28;
//判断是否为闰年
if(year%4==0&&year%100!=0||year%400==0)
{
feb=29;
}
switch(month)
{
case 12:
day+=30;
case 11:
day+=31;
case 10:
day+=30;
case 9:
day+=31;
case 8:
day+=31;
case 7:
day+=30;
case 6:
day+=31;
case 5:
day+=30;
case 4:
day+=31;
case 3:
day+=feb;
case 2:
day+=31;
case 1:
day+=0;
default:
break;
}
day+=date;
return day;
}
int main()
{
printf("2014,3,3是一年中的第%d天\n",day(2014,3,3));
return 0;
}
其实以前case我也没有这样用,不加break可以累加。
另外一种写法不用case
#include <stdio.h>
#include <stdlib.h>
//平年2月28天,闰年2月29天
int day(int year,int month,int date)
{
int day=0;
int i;
int months[]={31,28,31,30,31,30,31,31,30,31,30,31};
if(year%4==0&&year%100!=0||year%400==0)
{
months[1]=29;
}
for(i=1;i<month;++i)
{
day+=months[i-1];
}
day+=date;
return day;
}
int main()
{
printf("2014,3,3是一年中的第%d天\n",day(2014,3,3));
return 0;
}