double x;
cin>>x;
if( x > 1.7976931348623157e+308 || x < -1.7976931348623157e+308 )
{
cout<<"value not in range"<<endl;
exit(1);
}
Is there like a DOUBLE_MAX or DOUBLE_MIN and would I need to include any header files?
double x;
cin>>x;
if( x > 1.7976931348623157e+308 || x < -1.7976931348623157e+308 )
{
cout<<"value not in range"<<endl;
exit(1);
}
Is there like a DOUBLE_MAX or DOUBLE_MIN and would I need to include any header files?
There are constants for the largest and smallest double types, but since x
is of type double, x cannot be larger or smaller than these values! If you wish to compare an inputted value to these limits you'll need to parse the string yourself and check for overflow.
The header <cfloat>
is equivalent to the C header <float.h>
and contains DBL_MIN
and DBL_MAX
among many other things. The integer limits (<limits.h>
in C) are held in <climits>
.
This is detailed in 18.3.2 of the C++0x draft. But, as pointed out elsewhere, a double cannot hold values outside this range anyway. You would have to use a "larger" type such as long double (although, according to the standard, that could be the same size as double, so may not necessarily help).
Here's a full sample program for your enjoyment :-)
#include <iostream>
#include <cfloat>
int main (void) {
long double bignum;
std::cout << "Enter number: ";
std::cin >> bignum;
if ((bignum > (long double)DBL_MAX) || (bignum < (long double)DBL_MIN)) {
std::cout << "Value not in range" << std::endl;
} else {
double x = bignum;
std::cout << "Number was " << x << std::endl;
}
return 0;
}
with accompanying transcript:
$ ./qq.exe
Enter number: 1.7976931348623157e+308
Number was 1.79769e+308
$ ./qq.exe
Enter number: 1.7976931348623158e+308
Value not in range