宽度小于printf()的精度是多少?

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)

在第一种情况下,精度小于指定的宽度,实际上增加了前导空间.然而,当精度更高时,宽度似乎是多余的.

是否有这样的格式的原因?

Pra*_*ian 5

仅当打印数字的总宽度小于指定宽度时,宽度格式说明符才会影响输出。显然,当精度设置为大于或等于宽度时,这种情况永远不会发生。因此,在这种情况下宽度规范是没有用的。

这是MSDN上的一篇文章;最后一句话解释了这一点。

不存在或较小的字段宽度不会导致字段截断;如果转换结果比字段宽度宽,则字段将扩展以包含转换结果。