39

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

#include<iostream>
#include<limits>

using namespace std;

int main() {
  cout << "int: " << numeric_limits<int>::min() << " "
       << "float: " << numeric_limits<float>::min() << " "
       << "double: " << numeric_limits<double>::min() << "\n";
  return 0;
}

Output:

int: -2147483648 float: 1.17549e-38 double: 2.22507e-308

From cppreference:

Returns the minimum finite value representable by the numeric type T.

For floating-point types with denormalization, min returns the minimum positive normalized value. Note that this behavior may be unexpected, especially when compared to the behavior of min for integral types. To find the value that has no values less than it, use numeric_limits::lowest.

min is only meaningful for bounded types and for unbounded unsigned types, that is, types that represent an infinite set of negative values have no meaningful minimum.

4

2 回答 2

46

根据定义,对于浮点类型,min返回该类型可以编码的最小正值,而不是最低的。

如果您想要最低值,请numeric_limits::lowest改用。

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

至于为什么会这样,我只能推测标准委员会需要一种方法来表示所有不同原生类型的所有形式的极值。在整数类型的情况下,只有两种极端类型:最大正数和最大负数。对于浮动还有另一个:最小的可能。

如果您认为语义有点混乱,我同意。C 标准中相关 s 的语义#define以大致相同的方式混淆。

于 2013-06-12T16:14:14.010 回答
6

It's unfortunate, but behind similar names completely different meaning lies. It was kinda carried over from C, where DBL_MIN and INT_MIN has the very same "problem".

As not much can be done, just remember what means what.

于 2013-06-12T16:20:01.007 回答