C ++:什么是“float”的printf()格式规范? [英] C++: What is the printf() format spec for "float"?
问题描述
C ++: printf()
格式规范是 float
(Visual C ++)
C++: What is the printf()
format spec for float
? (Visual C++)
以前我用%g
代替 float
和%lg
为 double
。
看起来规格已更改, float
未定义, double
是%g
。
It looks like the spec changed and float
is undefined and double
is %g
.
我有内存中的位,我打印出来,所以铸造不是选项。
I have bits in memory that I am printing out so casting is not an option.
有没有办法可以使用 printf打印出
? float
)
Is there a way that I can print out float
values using printf()
?
更新:
是为在嵌入式系统上使用的单元测试通用C ++库编写的。
这是我必须做的,让 float
工作。
代码在模板函数中:
This code was written for unit testing generic C++ libs used on an embedded system.
Here's what I had to do to get the float
to work.
The code is in a template function:
template <typename T,typename TTYP,typename Ttyp,int bits,bool IsSigned>
Error testMatrixT()
{ ...
:
if (typeid(Ttyp) == typeid(float)) {
float64 c = *(float32*)&Tp(row,col);
float64 a1 = *(float32*)&Arg1(row,col);
float64 a2 = *(float32*)&Arg2(row,col);
float64 e = *(float32*)&Exp(row,col);
m_b = (c == e);
_snprintf(m_acDiag, sizeof(m_acDiag)-1
, "add(Arg1,Arg2): arg1=%g, arg2=%g, Expected=%g, Actual=%g, Result: %s"
, a1, a2, e, c, BOOL_PF(m_b));
} else {
...
很丑陋不是吗?使用浮点作为args给出错误的输出。也许是因为使用 _snprintf()
?
多年前,我会使用%lg
,那就行了。不再。
Pretty ugly isn't it? Using floats as args give bad output. Maybe due to using _snprintf()
?
Years ago I would use %lg
and it would be OK. Not anymore.
推荐答案
double和float使用与 printf
(%a
,%e
,%f
和%g
)。这是因为 printf
是一个可变函数。任何float参数在调用之前隐式提升为double;你不能实际传递一个浮动到 printf
。
double and float use the same format specifiers with printf
(%a
, %e
, %f
, and %g
). This is because printf
is a variadic function. Any float arguments are implicitly promoted to double before the call; you can't actually pass a float to printf
.
这篇关于C ++:什么是“float”的printf()格式规范?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!