c++ - %g 精度问题

标签 c++ c

当我使用 printf("%.6g\n",36.666666662); 时,我期望输出 36.666667。但实际输出是36.6667

我给出的格式有什么问题?我的目标是有 6 个小数位

最佳答案

这是正确的行为。根据cplusplus.com :

For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point.

For g and G specifiers: This is the maximum number of significant digits to be printed.

如果您使用 f 而不是 g 那么它将按您预期的那样工作。


示例代码

#include <stdio.h>

int main(void) {
    printf("%.6g\n", 36.666666662);
    printf("%.6f\n", 36.666666662);
    return 0;
}

结果

36.6667
36.666667

在线查看它:ideone .

关于c++ - %g 精度问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13878369/

相关文章:

c++ - 如何使用 3d 的 max 2016 SDK (C++) 在插件中添加保存文件对话框?

c++ - 如何复制具有嵌套类(包含指向外部类的指针成员)的类的实例?

c++ - 如何使用 OpenCV 2.3.1 连接网络摄像机?

c - 带有 typedef 的结构并声明一个函数

C 编程 - 验证 int 输入使其不是字符

c - 在 C 中使用嵌套循环

c++ - 如何简单地创建一个 ASN.1 DER 编码的 blob

c++ - 在 visual studio 中为 usertype.dat 中的关键字赋值?

c++ - 标准是否定义了 `a[i]` 的类型,其中 `a` 是 `T [M][N]`?

c - 在 C 中使用 enum 和 int 变量的区别