gpt4 book ai didi

c - time.h 是否允许闰年 C

转载 作者:太空宇宙 更新时间:2023-11-04 05:39:02 28 4
gpt4 key购买 nike

我正在寻找一种方法来找出两个日期之间的差异。该解决方案需要考虑闰年。请参阅下面的两个代码块。 2012 年是闰年而 2013 年不是,所以我不明白为什么两个程序都输出“32 天差异”。如果 time.h 确实考虑到了闰年,它们肯定应该不同吗?

第一个:

#include <stdio.h>  
#include <time.h>
int main ()
{
struct tm start_date;
struct tm end_date;
time_t start_time, end_time;
double days;

start_date.tm_hour = 0; start_date.tm_min = 0; start_date.tm_sec = 0;
start_date.tm_mon = 2; start_date.tm_mday = 1; start_date.tm_year = 112;

end_date.tm_hour = 0; end_date.tm_min = 0; end_date.tm_sec = 0;
end_date.tm_mon = 3; end_date.tm_mday = 1; end_date.tm_year = 112;

start_time = mktime(&start_date);
end_time = mktime(&end_date);

days = difftime(end_time, start_time) / 86400;

printf ("%.f days difference\n", days);

return 0;
}

第二个:

#include <stdio.h>  
#include <time.h>
int main ()
{
struct tm start_date;
struct tm end_date;
time_t start_time, end_time;
double days;

start_date.tm_hour = 0; start_date.tm_min = 0; start_date.tm_sec = 0;
start_date.tm_mon = 2; start_date.tm_mday = 1; start_date.tm_year = 113;

end_date.tm_hour = 0; end_date.tm_min = 0; end_date.tm_sec = 0;
end_date.tm_mon = 3; end_date.tm_mday = 1; end_date.tm_year = 113;

start_time = mktime(&start_date);
end_time = mktime(&end_date);

days = difftime(end_time, start_time) / 86400;

printf ("%.f days difference\n", days);

return 0;
}

最佳答案

Buddy 只需尝试以下操作(将您的月份分别更改为 1 和 2,而不是 2 和 3,它会给您正确的结果,此更改已经过测试)。

根据 Joachim 和 Floris 的说法,tm_mon 成员的月份为零,您计算的是 3 月 1 日和 4 月 1 日之间的差异,而不是 2 月 1 日和 3 月 1 日之间的差异。

  start_date.tm_hour = 0;  start_date.tm_min = 0;  start_date.tm_sec = 0;
start_date.tm_mon = 1; start_date.tm_mday = 1; start_date.tm_year = 112;

end_date.tm_hour = 0; end_date.tm_min = 0; end_date.tm_sec = 0;
end_date.tm_mon = 2; end_date.tm_mday = 1; end_date.tm_year = 112;

关于c - time.h 是否允许闰年 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24405822/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com