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 值


基础教程推荐
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01