Bug*_*boy 7 c++ formatting printf
我看到一些代码看起来像:
fprintf(fd, "%4.8f", ptr->myFlt);
Run Code Online (Sandbox Code Playgroud)
这些天我没有使用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;
}
Run Code Online (Sandbox Code Playgroud)
它给出了以下输出:
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<
Run Code Online (Sandbox Code Playgroud)
在第一种情况下,精度小于指定的宽度,实际上增加了前导空间.然而,当精度更高时,宽度似乎是多余的.
是否有这样的格式的原因?
| 归档时间: |
|
| 查看次数: |
1721 次 |
| 最近记录: |