再之前我们介绍了2种计算日期差值的方法,最后我们来介绍另外1种方式。
其思路主要是将输入的日期转换为与公元1年相隔的日期总数,然后用2个日期数相减,从而得到两者之间相隔的天数。
下面是实现的代码:
#include <stdio.h>
#include <math.h>
int isLeap(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
int get_days(int year, int month, int day) {
int months[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int total = day - 1;
int b = isLeap(year);
year--;
int k = year / 4 - year / 100 + year / 400;
total += (year - k) * 365 + k * 366;
for (int i = 1; i < month; ++i) {
total += months[i];
}
// 补上一天
if (month > 2 && b > 0) {
total += 1;
}
return total;
}
int main() {
int year, month, day;
while (scanf("%4d%2d%2d", &year, &month, &day) != EOF) {
int d1 = get_days(year, month, day);
scanf("%4d%2d%2d", &year, &month, &day);
int d2 = get_days(year, month, day);
printf("%d\n", abs(d2 - d1)+1);
}
}
对于1个输入的年,我们计算到该年为止一共有多少个闰年,将其存储在变量k中。
然后使用输入的年减去闰年的数从而得到平年的年数,将其乘以365天,再与闰年的数量相乘后相加从而得到最终年的总天数。
最后是对月份及天数的累加,从而得到最终间隔的天数。
这种方式实际上跟解法二执行效率没有太大的差别,执行速度会稍微快点,因为避免了排序及循环月份遍历的过程。
最后是通过后的结果: