在 printf() 中,宽度小于精度有什么意义?

What's the point of a width smaller than a precision in printf()?

本文关键字:精度 什么 小于 printf      更新时间:2023-10-16

我遇到一些代码,其中一行看起来像:

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<

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

这样的格式有什么原因吗?

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

这是一篇来自MSDN;最后一句解释了。

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

也许是程序员的错误?也许他们交换了%8.4f或者他们实际上想要交换%12.8f甚至%012.8f

参见示例代码:

#include <stdio.h>
int main()
{
    printf("Seems unnecessary when decimals are greater: >%4.8f<n", 3.4567);
    printf("Seems unnecessary when decimals are greater: >%8.4f<n", 3.4567);
    printf("Seems unnecessary when decimals are greater: >%12.4f<n", 3.4567);
    printf("Seems unnecessary when decimals are greater: >%012.4f<n", 3.4567);
    return 0;
}

输出
Seems unnecessary when decimals are greater: >3.45670000<
Seems unnecessary when decimals are greater: >  3.4567<
Seems unnecessary when decimals are greater: >      3.4567<
Seems unnecessary when decimals are greater: >0000003.4567<

可能只是猜测,但是:精度给小数一个长度,如果你有更多的小数,不会超过。同样,宽度可以防止你的号码占用比它应该占用的空间更少。如果你考虑某种带有数字的表,你只能在每行上的每列具有相同宽度时才能实现统一列,而不管它包含的数字是多少。

因此,在一些价格格式中需要精度,例如10.00€,而您总是需要2位小数。

对于你的特定行:我觉得你在这个特殊情况下的宽度说明符冗余。