gpt4 book ai didi

c - fprintf 和 difftime 疯狂

转载 作者:太空宇宙 更新时间:2023-11-04 07:36:25 26 4
gpt4 key购买 nike

为此搜索了答案,但找不到任何内容。我能找到的最接近的是 difftime returning 0 when there is clearly a difference其中有一个很好的解释,与如何将参数插入堆栈以及格式期望的内容有关,但我认为我的问题不同:

我已经尽可能简单地举了一个例子。假设我在 C 中有以下代码:

time_t starttime = time(NULL)
somefunction();
time_t newtime = time(NULL)

fprintf(stderr, "starttime %f and difftime %f\n", starttime, difftime(newtime, starttime));
fprintf(stderr, "difftime %f and starttime %f\n", difftime(newtime, starttime), starttime);
return 0;

somefunction 是运行 1 或 2 秒的函数。我得到的输出是:

starttime 2.000000 and difftime 0.000000
difftime 2.000000 and starttime 0.000000

我什至不知道从哪里开始我的问题。为什么我调换顺序,输出的值还是一样?此外,为什么其中一个值是 0?无论我使用 %f、%d、%lu、%llu 等,这都是一样的。对此有堆栈参数解释吗? fprintf 在内部到底在做什么?

谢谢。我浪费了太多的时间来调试这个,我真的很感激你的帮助!

最佳答案

"%f" 说明符不适用于您平台上的 time_t。据我所知,time_t 类型可以是整数或实数。

例如the POSIX standard只是说:

time_t and clock_t shall be integer or real-floating types.

试试这个:

/* Flawed bad and wrong. */
printf("%f\n", (double)starttime);

我看到有人建议将其转换为 uintmax_tunsigned long long 等。显然,真正的答案是 here :

There is no uniform way to printf() time_t, period. You are not supposed to do this - you're don't even need to know what a time_t is internally. Suggested alternatives include ctime() and strftime(). Please use these to keep code portable.

关于c - fprintf 和 difftime 疯狂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8456382/

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