为什么 numeric_limits::max() > numeric_limits::无穷大()?
我正在阅读在C++中将int设置为无穷大。我明白,当需要真正的无穷大时,应该使用 numeric_limits
;我猜其背后的基本原理是,通常整型没有指定用于表示特殊状态的值,例如 NaN、Inf 等,就像 IEEE 754 浮点数那样(同样,C++ 也没有) t 两者都不要求 - 使用的 int
和 float
留给实现);但 max > 仍然具有误导性。对于给定类型,无穷大。我试图理解标准中此调用背后的基本原理。如果无限对于一个类型来说没有意义,那么是否应该禁止它而不是使用一个标志来检查其有效性?
I was reading Setting an int to Infinity in C++. I understand that when one needs true infinity, one is supposed to use numeric_limits<float>::infinity()
; I guess the rationale behind it is that usually integral types have no values designated for representing special states like NaN, Inf, etc. like IEEE 754 floats do (again C++ doesn't mandate neither - int
& float
used are left to the implementation); but still it's misleading that max > infinity
for a given type. I'm trying to understand the rationale behind this call in the standard. If having infinity
doesn't make sense for a type, then shouldn't it be disallowed instead of having a flag to be checked for its validity?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
函数
numeric_limits::infinity()
对于numeric_limits::has_infinity
返回的
T
有意义正确。如果是
T=int
,则返回false
。因此这种比较没有意义,因为numeric_limits::infinity()
不会返回任何有意义的值进行比较。The function
numeric_limits<T>::infinity()
makes sense for thoseT
for whichnumeric_limits<T>::has_infinity
returnstrue
.In case of
T=int
, it returnsfalse
. So that comparison doesn't make sense, becausenumeric_limits<int>::infinity()
does not return any meaningful value to compare with.如果您阅读此参考,您将看到一个表格,显示整数类型的无穷大为零。这是因为根据定义,C++ 中的整数类型不可能是无限的。
If you read e.g. this reference you will see a table showing infinity to be zero for integer types. That's because integer types in C++ can't, by definition, be infinite.
相反,假设标准确实保留了一些值来表示无穷大,并且
numeric_limits::infinity() > numeric_limits::max()
。这意味着int
的某个值会大于max()
,即int
的某个可表示值大于int 的最大可表示值。显然,无论标准指定哪种方式,都会违反一些自然理解。要么
inifinity() <= max()
,或者存在 x 使得int(x) > >最大()。标准必须选择要违反哪条自然规则。
我相信他们的选择是明智的。
Suppose, conversely, the standard did reserve some value to represent inifity, and that
numeric_limits<int>::infinity() > numeric_limits<int>::max()
. That means that there would be some value ofint
which is greater thanmax()
, that is, some representable value ofint
is greater than the greatest representable value of int.Clearly, whichever way the Standard specifies, some natural understanding is violated. Either
inifinity() <= max()
, or there exists x such thatint(x) > max()
. The Standard must choose which rule of nature to violate.I believe they chose wisely.
numeric_limits::infinity()
返回正无穷大的表示形式(如果可用)。对于整数,不存在正无穷大:
打印
numeric_limits<int>::infinity()
returns the representation of positive infinity, if available.In case of integers, positive infinity does not exists:
prints