C/C++ NaN constant (literal)?

后端 未结 5 852
孤独总比滥情好
孤独总比滥情好 2020-11-29 21:20

Is this possible to assign a NaN to a double or float in C/C++? Like in JavaScript you do: a = NaN. So later you can chec

相关标签:
5条回答
  • 2020-11-29 21:45

    As others have pointed out you are looking for std::numeric_limits<double>::quiet_NaN() although I have to say I prefer the cppreference.com documents. Especially because this statement is a little vague:

    Only meaningful if std::numeric_limits::has_quiet_NaN == true.

    and it was simple to figure out what this means on this site, if you check their section on std::numeric_limits::has_quiet_NaN it says:

    This constant is meaningful for all floating-point types and is guaranteed to be true if std::numeric_limits::is_iec559 == true.

    which as explained here if true means your platform supports IEEE 754 standard. This previous thread explains this should be true for most situations.

    0 讨论(0)
  • 2020-11-29 21:47

    Is this possible to assign a NaN to a double or float in C ...?

    Yes, since C99, (C++11) <math.h> offers the below functions:

    #include <math.h>
    double nan(const char *tagp);
    float nanf(const char *tagp);
    long double nanl(const char *tagp);
    

    which are like their strtod("NAN(n-char-sequence)",0) counterparts and NAN for assignments.

    // Sample C code
    uint64_t u64;
    double x;
    x = nan("0x12345");
    memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
    x = -strtod("NAN(6789A)",0);
    memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
    x = NAN;
    memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
    

    Sample output: (Implementation dependent)

    (7ff8000000012345)
    (fff000000006789a)
    (7ff8000000000000)
    
    0 讨论(0)
  • 2020-11-29 21:48

    This can be done using the numeric_limits in C++:

    http://www.cplusplus.com/reference/limits/numeric_limits/

    These are the methods you probably want to look at:

    infinity()  T   Representation of positive infinity, if available.
    quiet_NaN() T   Representation of quiet (non-signaling) "Not-a-Number", if available.
    signaling_NaN() T   Representation of signaling "Not-a-Number", if available.
    
    0 讨论(0)
  • 2020-11-29 21:57

    yes, by the concept of pointer you can do it like this for an int variable:

    int *a;
    int b=0;
    a=NULL; // or a=&b; for giving the value of b to a
    if(a==NULL) 
      printf("NULL");
    else
      printf(*a);
    

    it is very simple and straitforward. it worked for me in Arduino IDE.

    0 讨论(0)
  • 2020-11-29 21:59

    In C, NAN is declared in <math.h>.

    In C++, std::numeric_limits<double>::quiet_NaN() is declared in <limits>.

    But for checking whether a value is NaN, you can't compare it with another NaN value. Instead use isnan() from <math.h> in C, or std::isnan() from <cmath> in C++.

    0 讨论(0)
提交回复
热议问题