目录
有两个日期,求两个日期之间的天数,如果两个日期是连续的我们规定他们之间的天数为两天
有多组数据,每组数据有两行,分别表示两个日期,形式为YYYYMMDD
每组数据输出一行,即日期差值
输入:
20110412 20110422输出:
11
AC代码~
#include<stdio.h>
int dayTab[2][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}
};
int IsLeapYear(int n) {
if ((n % 400 == 0) || (n % 4 == 0 && n % 100 != 0) )
return 1;
return 0;
}
int main() {
char s1[10];
char s2[10];
int y1, y2, m1, m2, d1, d2;
while (scanf("%s%s", s1, s2) != EOF) {
sscanf(s1, "%4d%2d%2d", &y1, &m1, &d1);
sscanf(s2, "%4d%2d%2d", &y2, &m2, &d2);
int total1 = 0; // 记录第一个日期相对于0000 00 00 的差值
int total2 = 0; // 记录第二个日期相对于0000 00 00 的差值
for (int i = 0; i <= y1; i++) {
if (IsLeapYear(y1))
total1 += 366;
else
total1 += 365;
}
for (int i = 1; i < m1; i++)
total1 += dayTab[IsLeapYear(y1)][i];
total1 += d1;
for (int i = 0; i <= y2; i++) {
if (IsLeapYear(y2))
total2 += 366;
else
total2 += 365;
}
for (int i = 1; i < m2; i++)
total2 += dayTab[IsLeapYear(y2)][i];
total2 += d2;
printf("%d\n", total2 - total1 + 1); // 结果就是两个差值相减+1
}
return 0;
}