如何检查双精度变量中的 inf(和 | 或)NaN

2024-01-28

考虑以下代码:

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

template<class T>
bool IsNaN(T t)
{
    return t != t;
}

int main(int argc, char**argv)
{
    double d1, d2;
    sscanf(argv[1], "%f", &d1);
    sscanf(argv[2], "%f", &d2);

    double dRes = d1/d2;

    cout << "dRes = " << dRes << "\n";

    if(IsNaN(dRes))
        cout << "Is NaN\n";
    else
        cout << "Not NaN\n";

}

有几个问题:

  1. 当我传递 0 和 0 作为参数时,它输出dRes = inf。但我期待着dRes = NaN或类似的东西。
  2. NaN 可以用双变量表示吗?就此而言,有什么变量吗?
  3. 当我将 d1,d2,dRes 的数据类型更改为 int 并传递 0 和 0 时,我得到了Floating exception。有什么不同?
  4. 如何检查变量的值是否等于inf?

  1. 使用时scanf() double应该阅读使用%lf, not %f. %f将输入转换为 32 位float,因此变量的前 32 位将填充一些无效数据,而后 32 位将被保留为垃圾。

  2. Yes. #include <limits>, then std::numeric_limits<double>::quiet_NaN() http://en.cppreference.com/w/cpp/types/numeric_limits。一些编译器(例如 gcc)还提供NAN宏在<cmath> http://www.gnu.org/s/libc/manual/html_node/Infinity-and-NaN.html.

  3. 整数类型没有 NaN 或无穷大。整数除以零会导致异常 (SIGFPE) http://en.wikipedia.org/wiki/SIGFPE.

  4. #include <cmath>, then std::isinf(x) http://en.cppreference.com/w/cpp/numeric/math/isinf. Use std::isfinite(x) http://en.cppreference.com/w/cpp/numeric/math/isfinite确保x不是 NaN 或 Infinity。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何检查双精度变量中的 inf(和 | 或)NaN 的相关文章

随机推荐