[英]Erroneous clock_t output value on printf
I have the following code: 我有以下代码:
#include <stdio.h>
#include <time.h>
clock_t a;
void f(void) {
a = clock();
printf("in f(): %g\n", a);
}
void main(void) {
f();
printf("in main(): %g\n", a);
}
Compiling it with MinGW gcc and running it produces output similar to this: 用MinGW gcc编译并运行它会产生类似于以下的输出:
in f(): -1.#QNAN
in main(): 1.49845e-307
Question : Why does a
contain -1.#QNAN
? 问题 :为什么
a
包含-1.#QNAN
While I understand what it means , I do not see what went wrong in the code. 虽然我明白这意味着什么,但是我看不出代码出了什么问题。 At first, I speculated that it has something to do with the printing format specifier for type
clock_t
, but answers from this stackoverflow thread says otherwise. 最初,我推测它与
clock_t
类型的打印格式说明符有关,但是从该stackoverflow线程得到的答案则相反。 Even to make sure, I did a quick digging in the standard headers and found out that clock_t
is a typedef for long
(at least on my machine), which means that there is nothing wrong with regards to displaying the value. 甚至可以确定的是,我快速浏览了标准标头,发现
clock_t
long
是typedef(至少在我的机器上),这意味着在显示值方面没有任何错误。 Could it be a bug in the clock()
function? 可能是
clock()
函数中的错误吗?
Edit : Just after reading the comments, I realized that my actual problem is that I was expecting a
to be some super small floating-point value so badly that I forgot clock_t
is, as I said, defined on my machine as of type long
. 编辑 :刚读完注释,我意识到我的实际问题是我期望
a
成为一个非常小的浮点值,以至于我忘了在我的机器上将clock_t
定义为long
类型,就像我说的那样。 Sorry for the bother and thank you all for your time. 抱歉打扰了,谢谢大家的时间。
Please always take a look at your compiler warning: 请始终查看您的编译器警告:
warning: format specifies type 'double' but the argument has type
'clock_t' (aka 'unsigned long') [-Wformat]
printf("in f(): %g\n", a);
~~ ^
%lu
Compiler even tells you how to fix. 编译器甚至告诉您如何修复。 In short, you can't specify a
double
to printf()
when the data is unsigned long
. 简而言之,当数据为
unsigned long
时,不能为printf()
指定一个double
。
%g
is for printing floating point numbers, but you passed a clock_t
(which can be any arithmetic type; such as a 32 bit integer). %g
用于打印浮点数,但是您传递了clock_t
(可以是任何算术类型;例如32位整数)。
You need to cast to a double
if you want to use %g
: 如果要使用
%g
则需要转换为double
:
printf("in main(): %g\n", static_cast<double>(a));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.