c - Difftime 给出的值大于预期值
问题描述
当我打印 difftime 的结果时,我得到结果:-4334284568731237.000000。为什么是这样?
//time1 and time2 are both of type time_t
time_t temp;
char val[] = "06:02";
struct tm tm;
strptime(val, "%H:%M", &tm);
temp = mktime(&tm);
items[0].time1 = temp;
char val2[] = "06:43";
struct tm tm;
strptime(val2, "%H:%M", &tm);
temp = mktime(&tm);
items[0].time2 = temp;
printf("%f\n", difftime(items[0].time1, items[0].time2));
解决方案
我假设tm
变量是在块范围内声明的,具有自动存储持续时间。
为什么是这样?
您只需设置小时和分钟:
struct tm tm; // uninitialized
strptime(val2, "%H:%M", &tm); // sets only tm.tm_hour and tm.tm_min
strptime
不初始化tm
,只存储它读取的内容。的其余成员struct tm
未初始化,因此它们具有“不确定”值 - 任何值。因此,第tm
一个年份的值可能与另一个年份不同,这可能会导致解析时返回tm
的内容有很大差异。mktime
tm
从strptime
手册页:tm should be initialized before the call
。所以在调用之前初始化结构strptime
:
struct tm tm = {0};
strptime(val2, "%H:%M", &tm);
推荐阅读
- mongodb - 返回数组数组作为 mongoose 中查询的响应
- amazon-web-services - AWS CloudFormation 堆栈名称和资源名称之间的关系
- vba - 关闭主窗体时可以从所有子窗体中删除源对象吗?
- c# - 是否可以在 IEntityTypeConfiguration 中引用相关实体
配置方法? - php - Phpspreadsheet 转换后的文件应具有包含相同值的附加新列
- c++ - 如何找到当前硬件线程的 L3 缓存索引和 NUMA 节点索引
- python - 使用字典值创建新列
- gstreamer - 使用 gstreamer 获得确定性时间
- c# - 列表框项目初始化,但一旦选择了一个,我不知道如何重置没有选择任何项目的列表框
- javascript - 如何运行每 30 秒调用一次 axios 的函数