check NaN number

后端 未结 3 1854
情话喂你
情话喂你 2021-01-03 20:57

Is it possible to check if a number is NaN or not?

3条回答
  •  猫巷女王i
    2021-01-03 21:36

    Yes, by use of the fact that a NaN is not equal to any other number, including itself.

    That makes sense when you think about what NaN means, the fact that you've created a value that isn't really within your power to represent with "normal" floating point values.

    So, if you create two numbers where you don't know what they are, you can hardly consider them equal. They may be but, given the rather large possibility of numbers that it may be (infinite in fact), the chances that two are the same number are vanishingly small :-)

    You can either look for a function (macro actually) like isnan (in math.h for C and cmath for C++) or just use the property that a NaN value is not equal to itself with something like:

    if (myFloat != myFloat) { ... }
    

    If, for some bizarre reason, your C implementation has no isnan (it should, since the standard mandates it), you can code your own, something like:

    int isnan_float (float f) { return (f != f); }
    

提交回复
热议问题