What’s the best, platform-independent way to obtain the maximum value that can be stored in a float
in C++?
This representation gives a range of approximately 3.4E-38 to 3.4E+38 for type float. You can declare variables as float or double, depending on the needs of your application.
What will be maximum size of a float variable? A signed 32-bit integer variable has a maximum value of 231 − 1 = 2,147,483,647, whereas an IEEE 754 32-bit base-2 floating-point variable has a maximum value of (2 − 2−23) × 2127 ≈ 3.4028235 × 1038.
Difference between float and double in C/C++ float is a 32-bit IEEE 754 single precision Floating Point Number – 1 bit for the sign, 8 bits for the exponent, and 23* for the value.
The header float. h contains macros that expand to various limits and parameters of the standard floating-point types. The macros, as defined on ISO 9899:1999 section 5.2.
std::numeric_limits
std::numeric_limits<float>::max()
std::numeric_limits
// numeric_limits example
#include <iostream>
#include <limits>
using namespace std;
int main () {
cout << "Minimum value for float: " << numeric_limits<float>::min() << endl;
cout << "Maximum value for float: " << numeric_limits<float>::max() << endl;
cout << "Minimum value for double: " << numeric_limits<double>::min() << endl;
cout << "Maximum value for double: " << numeric_limits<double>::max() << endl;
return 0;
}
In C++ you can use the std::numeric_limits
class to get this sort of information.
If has_infinity
is true
(which will be true for basically all platforms nowadays), then you can use infinitity
to get the value which is greater than or equal to all other values (except NaNs). Similarly, its negation will give a negative infinity, and be less than or equal to all other values (except NaNs again).
If you want finite values, then you can use min
/max
(which will be less than or equal to/greater than or equal to all other finite values).
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