【问题标题】:why does std::numeric_limits<float>::min() differ in behavior when streamed to output with different functions?为什么 std::numeric_limits<float>::min() 在使用不同功能流式传输到输出时的行为不同?
【发布时间】:2016-12-25 06:40:32
【问题描述】:

我有一个奇怪的行为

 std::numeric_limits<float>::min()

当我调用 std::cout 时,我得到的输出值为 1.17549e-38

相比之下,当我使用

printf("%f", std::numeric_limits<float>::min());

我得到的值为 0.000000。

请注意,当我评估 (std::numeric_limits&lt;float&gt;::min() == std::numeric_limits&lt;float&gt;::min()) 时,我会得到 true(直观且合乎逻辑)

那么,谁能向我解释一下这种输出差异?

【问题讨论】:

    标签: c++ c++11 floating-point format-specifiers numeric-limits


    【解决方案1】:

    cppreference for numeric_limits:

    std::numeric_limits&lt;float&gt;::min() 返回FLT_MIN。

    使用%f显示的返回值(实际上不是0)实际上被格式化为固定的小数位数。 '%f' 格式以固定格式打印 6 位小数。

    你可以使用:

    %e=gives the scientific notation
    %g=handles large floating numbers
    

    【讨论】:

    • 有什么建议可以用 printf 修复这个输出吗?
    • 请改用%g 或%e。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多