C++:float 的 printf() 格式规范是什么?(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.
这篇关于C++:“float"的 printf() 格式规范是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
读取输入文件,最快的方法?read input files, fastest way possible?(读取输入文件,最快的方法?)
在 C++ 中读取格式化输入的最简单方法?The easiest way to read formatted input in C++?(在 C++ 中读取格式化输入的最简单方法?)
从 .txt 文件读取到 C++ 中的二维数组Reading from .txt file into two dimensional array in c++(从 .txt 文件读取到 C++ 中的二维数组)
如何在 C++ 中模拟按键按下How to simulate a key press in C++(如何在 C++ 中模拟按键按下)
为什么在 cin.ignore() 之后没有 getline(cin, var) 读取Why doesn#39;t getline(cin, var) after cin.ignore() read the first character of the string?(为什么在 cin.ignore() 之后没有 getline(cin, var) 读取
scanf 格式输入的 cin 类比是什么?What is the cin analougus of scanf formatted input?(scanf 格式输入的 cin 类比是什么?)