将数字与 NaN 进行比较的结果是什么?
What is the result of comparing a number with NaN?
举个例子
bool fun (double a, double b) {
return a < b;
}
如果任何参数是 NaN,fun
return 会怎样?这是未定义/实现定义的行为吗?
其他关系运算符和相等运算符会怎样?
C++ 标准仅仅说:
[expr.rel]/5 If both operands (after conversions) are of arithmetic or enumeration type, each of the operators shall yield true
if the specified relationship is true and false
if it is false.
所以基本上,如果 a
小于 b
,a < b
为真。
但是,该实现可能通过 numeric_limits::is_iec559
声明符合 IEC 559 aka IEEE 754 浮点运算标准。然后它受第 5.7 节和 table 4 中的该标准约束,这要求除涉及 NaN
的 !=
之外的所有比较报告 false
。 !=
涉及 NaN
份报告 true
错误。
确实没有 -NaN
这样的东西,尽管 NaN 值确实带有符号位和有效负载。但是为了算术目的,NaN 就是 NaN 就是 NaN。
任何与 NaN 相等或有序的比较都是错误的。
任何与 NaN 的比较(“!=”除外)returns false。
这是我构造的table:
+Dbl_Nan 0_Nan Inf_Nan NaN_NaN +Dbl_Inf +Dbl_-Inf Inf_-Inf Inf_Inf
-----------------------------------------------------------------------
> | False False False False False True True False
< | False False False False True False False False
== | False False False False False False False True
!= | True True True True True True True False
单击 here 了解 NaN 始终为假的原因。
举个例子
bool fun (double a, double b) {
return a < b;
}
如果任何参数是 NaN,fun
return 会怎样?这是未定义/实现定义的行为吗?
其他关系运算符和相等运算符会怎样?
C++ 标准仅仅说:
[expr.rel]/5 If both operands (after conversions) are of arithmetic or enumeration type, each of the operators shall yield
true
if the specified relationship is true andfalse
if it is false.
所以基本上,如果 a
小于 b
,a < b
为真。
但是,该实现可能通过 numeric_limits::is_iec559
声明符合 IEC 559 aka IEEE 754 浮点运算标准。然后它受第 5.7 节和 table 4 中的该标准约束,这要求除涉及 NaN
的 !=
之外的所有比较报告 false
。 !=
涉及 NaN
份报告 true
错误。
确实没有 -NaN
这样的东西,尽管 NaN 值确实带有符号位和有效负载。但是为了算术目的,NaN 就是 NaN 就是 NaN。
任何与 NaN 相等或有序的比较都是错误的。
任何与 NaN 的比较(“!=”除外)returns false。
这是我构造的table:
+Dbl_Nan 0_Nan Inf_Nan NaN_NaN +Dbl_Inf +Dbl_-Inf Inf_-Inf Inf_Inf
-----------------------------------------------------------------------
> | False False False False False True True False
< | False False False False True False False False
== | False False False False False False False True
!= | True True True True True True True False
单击 here 了解 NaN 始终为假的原因。