Obtain minimum NEGATIVE float value in C++

前端 未结 3 1727
猫巷女王i
猫巷女王i 2021-02-05 03:04

I was looking at std::numeric_limits::min/max() but it appears \'min()\' returns the smallest absolute value, not the lowest value. Is it safe

相关标签:
3条回答
  • 2021-02-05 03:29

    use std::numeric_limits::lowest()

    static _Ty __CRTDECL lowest() _THROW0()
        {   // return most negative value
        return (-(max)());
        }
    
    0 讨论(0)
  • 2021-02-05 03:34

    IEEE 754 floating point numbers use a sign bit for signed-ness (rather than something like twos complement), so if you're sure that your compiler/platform uses that representation (very common) then you can use -std::numeric_limits<float>::max() as you suspected.

    0 讨论(0)
  • 2021-02-05 03:42

    Yes, float is symmetric in minimum/maximum values.

    If you're using the lowest representable value as an initial value in searching a list for its maximum value, consider using infinity instead.

    std::numeric_limits<T>::has_infinity() will return true for any numeric type that has it and std::numeric_limits<T>::infinity() will return a value that always evaluates greater than any other non-NaN value for that type. This value can be negated and will evaluate less than anything else.

    0 讨论(0)
提交回复
热议问题