Sobes.tech
Junior

How can you check that no exception occurred when working with a double type?

sobes.tech AI

Answer from AI

Since double is a primitive type, operations with it do not generate C++ exceptions. However, special values such as:

  • NaN (Not a Number): the result of an invalid mathematical operation (e.g., dividing zero by zero).
  • Infinity: the result of dividing a non-zero number by zero.

Functions from <cmath> (or <math.h> in C) are used to check for these:

  • isnan(x): returns true if x is NaN.
  • isinf(x): returns true if x is infinity.
  • isfinite(x): returns true if x is neither NaN nor infinity.

Example usage:

#include <iostream>
#include <cmath>

int main() {
    double a = 0.0;
    double b = 0.0;
    double c = a / b; // Result is NaN

    double d = 1.0;
    double e = 0.0;
    double f = d / e; // Result is Infinity

    double g = 5.0;

    if (std::isnan(c)) {
        std::cout << "Variable c is NaN" << std::endl;
    }

    if (std::isinf(f)) {
        std::cout << "Variable f is Infinity" << std::endl;
    }

    if (std::isfinite(g)) {
        std::cout << "Variable g is finite" << std::endl;
    }

    return 0;
}