如何在double变量中检查inf(和|或)NaN

nak*_*iya 20 c++ linux floating-point g++

请考虑以下代码:

#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";

}
Run Code Online (Sandbox Code Playgroud)

几个问题:

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

ken*_*ytm 30

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

  2. 是.#include <limits>,然后std::numeric_limits<double>::quiet_NaN().一些编译器(例如gcc)也提供了NAN<cmath>.

  3. 整数类型没有NaN或无穷大.整数除以零将导致异常(SIGFPE).

  4. #include <cmath>那么std::isinf(x).使用std::isfinite(x),以确保x不NAN或无穷大.

  • @nakiya:不,浮点除法也是用硬件完成的.区别在于无限是用'int`表示的. (2认同)