为什么numeric_limits :: min为int返回一个负值,但为float / double返回一个正值? [英] Why does numeric_limits::min return a negative value for int but positive values for float/double?

查看:126
本文介绍了为什么numeric_limits :: min为int返回一个负值,但为float / double返回一个正值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么为什么numeric_limits :: min返回int的负值,但是返回正值,例如

 #include< iostream> ;? 
#include< limits>

使用命名空间std;

int main(){
cout<< int:<< numeric_limits< int> :: min()<<
<< 浮动:<< numeric_limits< float> :: min()<<
<< double:<< numeric_limits< double> :: min()<< \n;
返回0;
}

输出:

  int:-2147483648浮点数:1.17549e-38 double:2.22507e-308 

来自cppreference:


返回由数字类型T表示的最小有限值。 / p>

对于具有非规格化的浮点类型,min返回最小的
正规格化值。 请注意,这种行为可能是意想不到的
尤其是与整数类型的min行为相比。要使
找到不小于它的值,请使用
numeric_limits :: lowest



min仅对有界类型有意义,而
对无界无符号类型有意义,也就是说,表示
个无穷负值的类型没有有意义的最小值。



解决方案

按定义,对于浮动类型, min 返回类型可以编码的最小正值,而不是最低



如果您想要最小值,请使用 numeric_limits :: lowest



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



关于为什么,我只能推测标准委员会需要一种方法来代表所有形式的所有极端价值不同的本机类型。对于整数类型,只有两种极端:最大正数和最大负数。对于浮点数,还有另一个:最小的可能。



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


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.

解决方案

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.

这篇关于为什么numeric_limits :: min为int返回一个负值,但为float / double返回一个正值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆