C++:“float"的 printf() 格式规范是什么?

2021-12-22 00:00:00 format visual-c++ printf c++

C++:floatprintf() 格式规范是什么?(Visual C++)

C++: What is the printf() format spec for float? (Visual C++)

过去我用 %g 表示 float%lg 表示 double.

It used to be that I used %g for float and %lg for 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 {
    ...

很丑吧?使用浮点数作为参数会产生错误的输出.也许是因为使用 _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 是一个可变参数函数.在调用之前,任何浮点参数都被隐式提升为双精度;您实际上无法将浮点数传递给 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.

相关文章