-
题目描述:
-
有两个日期,求两个日期之间的天数,如果两个日期是连续的我们规定他们之间的天数为两天
-
输入:
-
有多组数据,每组数据有两行,分别表示两个日期,形式为YYYYMMDD
-
输出:
-
每组数据输出一行,即日期差值
-
样例输入:
-
20110412 20110422
-
样例输出:
-
11
1 #include <cstdio> 2 #include <cstdlib> 3 #include <cstring> 4 #include <string> 5 #include <cmath> 6 #include <algorithm> 7 8 #define MAX 10 9 using namespace std; 10 11 char date1c[MAX]; 12 char date2c[MAX]; 13 char tempc[MAX]; 14 15 int date1[MAX]; 16 int date2[MAX]; 17 18 int year1,month1,day1; 19 int year2,month2,day2; 20 21 int month[][13] = {{0,31,28,31,30,31,30,31,31,30,31,30,31},{0,31,29,31,30,31,30,31,31,30,31,30,31}}; 22 int dayCount[] = {365,366}; 23 24 int isR(int year) { 25 if(((year % 4 == 0) && (year % 100!= 0))||(year % 400 == 0)) { 26 return 1; 27 } 28 return 0; 29 } 30 int main(int argc, char const *argv[]) 31 { 32 while(scanf("%s %s",date1c,date2c) != EOF) { 33 if(strcmp(date1c,date2c) > 0) { 34 sscanf(date1c,"%s",tempc); 35 sscanf(date2c,"%s",date1c); 36 sscanf(tempc,"%s",date2c); 37 } 38 for(int i = 0; i < 8; i++) { 39 date1[i] = date1c[i] - '0'; 40 date2[i] = date2c[i] - '0'; 41 } 42 year1 = date1[0]*1000+date1[1]*100+date1[2]*10+date1[3]; 43 month1 = date1[4]*10 + date1[5]; 44 day1 = date1[6]*10+date1[7]; 45 //printf("%d %d %d\n",year1,month1,day1); 46 47 year2 = date2[0]*1000+date2[1]*100+date2[2]*10+date2[3]; 48 month2 = date2[4]*10 + date2[5]; 49 day2 = date2[6]*10+date2[7]; 50 51 //printf("%d %d %d\n",year2,month2,day2); 52 53 int yd1 = 0,yd2 = 0; 54 55 for(int i = 1; i < month1; i++) { 56 yd1 = yd1 + month[isR(year1)][i]; 57 } 58 yd1 = yd1 + day1; 59 //printf("%d\n",yd1); 60 for(int i = year1; i < year2; i++) { 61 yd2 = yd2 + dayCount[isR(i)]; 62 } 63 64 for(int i = 1; i < month2; i++) { 65 yd2 = yd2 + month[isR(year2)][i]; 66 } 67 //printf("%d\n",yd2); 68 yd2 = yd2 + day2; 69 int ans = yd2 - yd1 + 1; 70 printf("%d\n",ans); 71 } 72 return 0; 73 }
用到第一年的第一天的时间差表示二者的时间差,自我感觉月份天数的表示法有些巧妙