您的位置:首页 > 编程语言 > C语言/C++

C语言实现某年某月某日是某年的第几天

2016-02-23 20:46 344 查看
看到这个标题,想实现这样的功能其实挺简单的,用C语言的switch语句加上闰年,平年条件的判断,再加上一定的逻辑可以轻松实现这样的函数,在linux内核中,存在判断闰年平年的接口,我将它移植出来后,写成一个宏,供计算天数的函数来调用,看看是不是可以实现,来,上代码:


#include<stdio.h>
#include<stdlib.h>
enum 
{
	zero = 0 ,NUM_TWO = 2, NUM_THR = 13 ,tw_e = 28 ,
	tw_n = 29 ,st_z = 30 , st_o = 31 ,
};
#define isleap(y) (((y) % 4) == 0 && (((y) % 100) != 0 || ((y) % 400) == 0))  //判断是闰年还是平年
static int years[NUM_TWO][NUM_THR]= 
{
	{zero,st_o,tw_e,st_o,st_z,st_o, \
	 st_z,st_o,st_o,st_z,st_o,st_z,st_o},
	{zero,st_o,tw_n,st_o,st_z,st_o, \
	 st_z,st_o,st_o,st_z,st_o,st_z,st_o}
};
static int Count(int year,int month,int day) ;
int main()
{
	int year,month,day,m;
	int day_num ;
	printf("please input (year-month-day)\n");
	scanf("%d-%d-%d",&year,&month,&day);  //按上面说的格式输入
	day_num = Count(year,month,day);      
	printf("day_num:%d\n",day_num);
	return 0;
}

static int Count(int year,int month,int day)
{
	int flag = 0 ;
	static int i ;
	if(isleap(year))  //判断是闰年还是平年
		flag=1;   //是闰年就把标志置一
	for(i=0;i<month;i++)  
		day+=years[flag][i]; //然后对应数组的行数来选择相应的天数进行累加
	return day ; //累加的结果返回,供主函数调用
}
运行结果:

我们可以看到,今天是2016年2月23日,是2016年的第54天!时间过得好快呀,两个月就快过去了噢,希望各位同行好好珍惜时间,有时间多多学习技术知识!


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: