[英]Why does numeric_limits::min return a negative value for int but positive values for float/double?
Why does numeric_limits::min return a negative value for int, but positive values for eg float and double? 为什么 numeric_limits :: min返回int的负值,但是例如float和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: 从cppreference:
Returns the minimum finite value representable by the numeric type T.
返回数值类型T表示的最小有限值。
For floating-point types with denormalization, min returns the minimum positive normalized value.
对于具有非规范化的浮点类型,min返回最小正标准化值。 Note that this behavior may be unexpected , especially when compared to the behavior of min for integral types.
请注意,此行为可能是意外的 ,尤其是与整数类型的min行为进行比较时。 To find the value that has no values less than it, use
numeric_limits::lowest
.要查找没有小于它的值的值,请使用
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.
min仅对有界类型和无界无符号类型有意义,也就是说,表示无限负值集的类型没有有意义的最小值。
By definition, for floating types, min
returns the smallest positive value the type can encode, not the lowest . 根据定义,对于浮点类型,
min
返回类型可以编码的最小正值,而不是最低值 。
If you want the lowest value, use numeric_limits::lowest
instead. 如果您想要最低值,请使用
numeric_limits::lowest
。
Documentation: http://en.cppreference.com/w/cpp/types/numeric_limits/min 文档: 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
#define
s in the C standard are muddled in much the same way. C标准中相关
#define
的语义大致相同。
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".
它有点从C继承,其中DBL_MIN和INT_MIN具有完全相同的“问题”。
As not much can be done, just remember what means what. 由于没有多少可以做,只记得什么意味着什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.