1. 程式人生 > >C語言實現某年某月某日是某年的第幾天

C語言實現某年某月某日是某年的第幾天

看到這個標題,想實現這樣的功能其實挺簡單的,用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天!時間過得好快呀,兩個月就快過去了噢,希望各位同行好好珍惜時間,有時間多多學習技術知識!得意