计算从出生到现在活了多少天
C语言写的,switch计算部分采用了一本狂人C书的类似写法,感觉很有创意。
1 #include <stdio.h> 2 3 4 typedef struct 5 { 6 int year; 7 int month; 8 int day; 9 }Date; 10 11 int date_minus(Date *now,Date *birth); 12 int numOfYear(Date *date); 13 int isLeapYear(int year); 14 15 int main(void) 16 { 17 Date birth={1993,4,4}; 18 Date now={2013,9,17}; 19 printf("%d\n",date_minus(&now,&birth)); 20 return 0; 21 } 22 23 int date_minus(Date *now,Date *birth) 24 { 25 26 int days; 27 int year; 28 29 if(now->year==birth->year) //同一年的情况 30 return numOfYear(now)-numOfYear(birth)+1; 31 else if(now->year<birth->year) 32 return -1; 33 34 //出生年的后几天 35 days=(isLeapYear(birth->year)?366:365)-numOfYear(birth)+1; 36 37 //中间年 38 for(year=birth->year+1;year < now->year;year++) 39 days+=isLeapYear(year)?366:365; 40 41 //今年的前几天 42 return days+numOfYear(now); 43 } 44 45 //一年中的第几天 46 int numOfYear(Date *date) 47 { 48 int days=date->day; 49 switch(date->month-1) 50 { 51 case 11:days+=30; 52 case 10:days+=31; 53 case 9:days+=30; 54 case 8:days+=31; 55 case 7:days+=31; 56 case 6:days+=30; 57 case 5:days+=31; 58 case 4:days+=30; 59 case 3:days+=31; 60 case 2:days+=isLeapYear(date->year) ? 29 :28; 61 case 1:days+=31; 62 return days; 63 } 64 return -1; 65 } 66 67 int isLeapYear(int year) 68 { 69 return (year%100 && year%4==0 )|| year%400==0; 70 }