Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
606 views
in Technique[技术] by (71.8m points)

visual c++ - C++: What is the printf() format spec for "float"?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...