我看到一些代码看起来像:
fprintf(fd,"%4.8f",ptr->myFlt);
这些天我没有使用C,我阅读了关于printf及其同类的文档,并了解到在这种情况下4是“宽度”,8是“精度”.宽度定义为输出占用的最小空间数,如果需要,填充带前导空格.
既然如此,我无法理解像“%4.8f”那样的模板是什么意思,
因为点之后的8(必要时填零)小数点已经确保满足并超过了4的宽度.所以,我在Visual C中写了一个小程序:
// Formatting width test
#include "stdafx.h"
int _tmain(int argc,_TCHAR* argv[])
{
printf("Need width when decimals are smaller: >%4.1f<\n",3.4567);
printf("Seems unnecessary when decimals are greater: >%4.8f<\n",3.4567);
printf("Doesn't matter if argument has no decimal places: >%4.8f<\n",(float)3);
return 0;
}
它给出了以下输出:
Need width when decimals are smaller: > 3.5< Seems unnecessary when decimals are greater: >3.45670000< Doesn't matter if argument has no decimal places: >3.00000000<
在第一种情况下,精度小于指定的宽度,实际上增加了前导空格.然而,当精度更高时,宽度似乎是多余的.
是否有这样的格式的原因?
解决方法
如果打印数字的总宽度小于指定宽度,则宽度格式说明符仅影响输出.显然,当精度设置为大于或等于宽度时,这种情况永远不会发生.因此,在这种情况下宽度规格是无用的.
Here’s来自MSDN的一篇文章;最后一句解释了它.
A nonexistent or small field width does not cause the truncation of a field; if the result of a conversion is wider than the field width,the field expands to contain the conversion result.