我发现一段代码有一行看起来像这样:
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<
在第一种情况下,精度小于指定的宽度,实际上会添加前导空格。然而,当精度更大时,宽度似乎是多余的。 这样格式化的原因是什么?
1234.87654321
。如果我在发明printf()
的时候,我可能会这样做(并想出其他字符来处理非浮点格式的总体宽度和精度)。 - Michael Burrc++
而不是c
? - leftaroundaboutprintf
函数并不相关。 - Puppy