我想了解为什么零填充对 printf 中的 %g 和 %f 格式有不同的作用。这是一个示例程序:
#include <stdio.h>
int main()
{
double d = 0.10000000000001;
printf("%04.2f\n", d);
printf("%04.2g\n", d);
return 0;
}
输出
0.10
00.1
这在 Windows 上的 VC++ 和 Linux 上的 gcc 中都是可重现的。
为什么会这样?这是正确的行为吗?
更新:我找到了答案,但我想我会把问题悬而未决...
最佳答案
这是正确的。根据 C99 7.19.6.1/8 中样式 g
的规范:
unless the # flag is used, any trailing zeros are removed from the fractional portion of the result and the decimal-point character is removed if there is no fractional portion remaining
虽然样式 f
没有指定删除尾随零。
关于c++ - printf %g 和 %f 之间的零填充差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15137008/