c++ - printf %g 和 %f 之间的零填充差异

标签 c++ printf

我想了解为什么零填充对 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/

相关文章:

c - union 中的 printf 值取决于格式

c++ - 将 std::string 转换为 const char* 供 printf 消费

php - 具有动态参数量的sprintf

c++ - 在这种情况下是否有必要使用 unique_ptr?

c++ - 了解 std::forward

c++ - 将文件中的矩阵加载到 vector 中

c++ - 如果我没有显式实例化 g++(使用 -fno-implicit-templates)从哪里获取模板定义?

c++ - 查找较新版本的应用程序

c - 当我告诉 printf 打印变量时会发生什么?

c++ - 错误 4 错误 C3861 : 'snprintf' : identifier not found