double返回一个正值

double返回一个正值

本文介绍了为什么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:


解决方案

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



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



文档:



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



如果您认为语义有点混乱,我同意。 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:

解决方案

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返回一个正值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 09:04