How to compare two NAN values in C++(如何在 C++ 中比较两个 NAN 值)
问题描述
我有一个代码区域产生 NAN 值的应用程序.我必须比较相等的值并在此基础上执行其余代码.如何比较 C++ 中的两个 NAN 值是否相等?
I have an application in which a code area produces NAN values. I have to compare the values for equality and based on that execute the rest of the code.How to compare two NAN values in C++ for equality?
推荐答案
假设 IEEE 754 浮点表示,您无法比较两个 NaN 值是否相等.NaN 不等于任何值,包括它自己.但是,您可以使用 std::isnan 来自 <cmath> 标头:
Assuming an IEEE 754 floating point representation, you cannot compare two NaN values for equality. NaN is not equal to any value, including itself. You can however test if they are both NaN with std::isnan from the <cmath> header:
if (std::isnan(x) && std::isnan(y)) {
// ...
}
不过,这仅在 C++11 中可用.在 C++11 之前,Boost Math Toolkit 提供了一些浮点分类器.或者,您可以通过与自身进行比较来检查值是否为 NaN:
This is only available in C++11, however. Prior to C++11, the Boost Math Toolkit provides some floating point classifiers. Alternatively, you can check if a value is NaN by comparing it with itself:
if (x != x && y != y) {
// ...
}
因为 NaN 是唯一不等于自身的值.过去,某些编译器将其搞砸了,但我目前不确定状态(它似乎与 GCC 一起正常工作).
Since NaN is the only value that is not equal to itself. In the past, certain compilers screwed this up, but I'm not sure of the status at the moment (it appears to work correctly with GCC).
MSVC 提供了一个 _isnan 函数.
MSVC provides a _isnan function.
最后一种选择是假设您知道表示是 IEEE 754 并进行一些位检查.显然这不是最便携的选择.
The final alternative is to assume you know the representation is IEEE 754 and do some bit checking. Obviously this is not the most portable option.
这篇关于如何在 C++ 中比较两个 NAN 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C++ 中比较两个 NAN 值
基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
