C++: What is the printf() format spec for quot;floatquot;?(C++:“float的 printf() 格式规范是什么?)
问题描述
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() 格式规范是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++:“float"的 printf() 格式规范是什么?


基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01