Why does numeric_limits::min return a negative value for int but positive values for float/double?

前端 未结 2 472
南方客
南方客 2020-12-29 02:32

Why does numeric_limits::min return a negative value for int, but positive values for e.g. float and double?

#include
#inclu         


        
2条回答
  •  旧时难觅i
    2020-12-29 03:05

    By definition, for floating types, min returns the smallest positive value the type can encode, not the lowest.

    If you want the lowest value, use numeric_limits::lowest instead.

    Documentation: http://en.cppreference.com/w/cpp/types/numeric_limits/min

    As for why it is this way, I can only speculate that the Standard committee needed to have a way to represent all forms of extreme values for all different native types. In the case of integral types, there's only two types of extreme: max positive and max negative. For floats there is another: smallest possible.

    If you think the semantics are a bit muddled, I agree. The semantics of the related #defines in the C standard are muddled in much the same way.

提交回复
热议问题