C ++: what is the printf () format specification for "float"?

C ++: what is the printf() format specification for float ? (Visual C ++)

I used to use %g for float and %lg for double .

It looks like the spec has changed, and float is undefined and double is %g .

I have a bit in memory that I print, so casting is not an option.

Is there a way to print float values ​​using printf() ?

Update:

This code was written for unit testing of common C ++ libraries used in the embedded system. Here is what I need to do to get the float to work. The code is in the template function:

 template <typename T,typename TTYP,typename Ttyp,int bits,bool IsSigned> Error testMatrixT() { ... 

Here is the code snippet:

 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 float as args gives a bad result. Perhaps due to the use of _snprintf() ? A few years ago I would use %lg and everything would be fine. No more.

+6
source share
6 answers

double and float use the same format specifiers with printf ( %a , %e , %f and %g ). This is because printf is a variational function. Any float arguments are implicitly advanced before doubling before the call; you cannot actually pass float to printf .

+16
source

To the question in the title: None / "% f"

To the question in the message body: Yes and no.

printf is a variational function. All float arguments are automatically raised to double s. You print the float by passing it to printf, but the float does not actually reach the printf function.

+4
source
 printf("float: %f", floatValue); 

or if you want a sample record:

 printf("float: %e", floatValue); 
+1
source

From: http://www.cplusplus.com/reference/clibrary/cstdio/printf/

% f Decimal floating point 392.65

+1
source

Others have indicated a format for printing float using printf , but since you are using C ++, my suggestion is to avoid this completely.

Use C ++ streams instead, then you don't have to worry about format specifiers. It is also type safe, but printf is not.

 #include <iostream> int main() { float f = 1.234; std::cout << f << std::endl; } 

If you have an array of bytes containing float, memcpy is in the variable float and use the code above.

+1
source

%g has always been the correct format for float or double (since float arguments are raised to double for variational functions like printf ).

%lg was added as a synonym for %g (in C99 I don't know when C ++ was or was adopted), probably for better symmetry with the *scanf family.

$Lg for a long double.

You can replace g with f or e above, depending on which output format you want.

+1
source

Source: https://habr.com/ru/post/895925/


All Articles