Junior
How can you verify that there are no exceptions when working with the double type?
sobes.tech AI
Answer from AI
You can use std::isfinite, std::isinf, and std::isnan from <cmath>.
#include <cmath> // For isfinite, isinf, isnan
#include <limits> // For numeric_limits
#include <iostream>
int main() {
double normal_value = 123.45;
double inf_value = std::numeric_limits<double>::infinity();
double nan_value = std::numeric_limits<double>::quiet_NaN();
// Check for finite number
if (std::isfinite(normal_value)) {
std::cout << "normal_value is a finite number\n";
}
// Check for infinity
if (std::isinf(inf_value)) {
std::cout << "inf_value is infinity\n";
}
// Check for NaN
if (std::isnan(nan_value)) {
std::cout << "nan_value is NaN\n";
}
return 0;
}
std::isfinite(x) returns true if x is neither infinity (+/-inf) nor NaN.
std::isinf(x) returns true if x is infinity (+/-inf).
std::isnan(x) returns true if x is Not-a-Number (NaN).
These functions allow detecting special floating-point values, which can result from incorrect operations (e.g., division by zero or sqrt(-1)) and are handled according to the IEEE 754 standard, not by exceptions in the usual sense.