如何检查双变量中的inf(和|或)NaN [英] How to check for inf (and | or) NaN in a double variable

查看:145
本文介绍了如何检查双变量中的inf(和|或)NaN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

#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时,得到一个 / code>。

  4. 如何检查变量的值是否等于 inf

  1. When I pass 0 and 0 as arguments, it outputs dRes = inf. But I was expecting dRes = NaN or something like that.
  2. Is NaN representable in double variables? For that matter, any variable?
  3. When I changed the data type of d1,d2,dRes to int and passed 0 and 0, I got a Floating exception. What is the difference?
  4. How to check if a variable's value is equal to inf?


推荐答案


  1. double 请使用%lf ,而不是%f 读取。 %f 将输入转换为32位 float ,因此您的变量的前32位将被填充带有一些无效数据,最后32位将作为垃圾留下。

  1. double should be read using %lf, not %f. %f will convert the input into a 32-bit float, so the first 32 bits of your variables will be filled with some invalid data, and the last 32 bits will be left as garbage.

是的。 #include< limits> 然后 std :: numeric_limits< double> :: quiet_NaN() 。某些编译器(例如gcc)还提供 NAN code>< cmath>

Yes. #include <limits>, then std::numeric_limits<double>::quiet_NaN(). Some compilers (e.g. gcc) also provides the NAN macro in <cmath>.

整数类型的NaN或无穷大。整数除以将导致异常(SIGFPE)

There is no NaN or infinity for integer types. Divide-by-zero for integer will cause an exception (SIGFPE).

#include< cmath> ,然后 std :: isinf(x) 。使用 std :: isfinite(x) 确保 x 不是NaN或无限。

#include <cmath>, then std::isinf(x). Use std::isfinite(x) to ensure x is not NaN or Infinity.

这篇关于如何检查双变量中的inf(和|或)NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆