C++: What is the printf()
format spec for float
? (Visual C++)
It used to be that I used %g
for float
and %lg
for double
.
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.
Is there a way that I can print out float
values using printf()
?
Update:
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()
{ ...
Here is a code snip:
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 {
...
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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…