Consider the following code:
#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"; }
Couple of questions:
dRes = inf
. But I was expecting dRes = NaN
or something like that.Floating exception
. What is the difference?inf
?To check whether a floating point or double number is NaN (Not a Number) in C++, we can use the isnan() function. The isnan() function is present into the cmath library. This function is introduced in C++ version 11.
In floating-point calculations, NaN is not the same as infinity, although both are typically handled as special cases in floating-point representations of real numbers as well as in floating-point operations.
In comparison operations, positive infinity is larger than all values except itself and NaN, and negative infinity is smaller than all values except itself and NaN. NaN is unordered: it is not equal to, greater than, or less than anything, including itself.
isinf() function in C++ isinf() is an inbuilt function in C++ which comes under header file, the function is used to check whether the variable passed in it is infinity or not, no matter if the number is negative infinity or positive infinity.
When using scanf()
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.
Yes. #include <limits>
, then std::numeric_limits<double>::quiet_NaN()
. Some compilers (e.g. gcc) also provides the NAN
macro in <cmath>
.
There is no NaN or infinity for integer types. Divide-by-zero for integer will cause an exception (SIGFPE).
#include <cmath>
, then std::isinf(x)
. Use std::isfinite(x)
to ensure x
is not NaN or Infinity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With