Just now I stumbled upon the fact, that the C++ function floor
returns the same type you pass to it, be it float
, double
or such.
According to this reference, the function returns a down rounded integral value. Why isn't this an integer?
floor() function returns the largest integer less than or equal to a given number.
Math. floor() function returns a double value equal to the nearest integer value, which is less than or equal to the double value passed to it as an argument.
Round(double) and Math. Round(decimal) will always return an integral value, these overloads still cannot return an integer value type.
It's for precision. The double data-type has a 53 bit mantissa. Among other things that means that a double can represent all whole up to 2^53 without precision loss.
Because an integral type can't necessarily hold the same integral values as a float
or double
.
int main(int argc, char *argv[]) {
std::cout << floor(std::numeric_limits<float>::max()) << std::endl;
std::cout << static_cast<long>(floor(std::numeric_limits<float>::max())) << ::endl;
}
outputs (on my x86_64 architecture)
3.40282e+38
-9223372036854775808
Additionally, floating-point values can hold NaN, +Inf, and -Inf, all of which are preserved by a floor()
operation. None of these values can be represented with an integral type.
int main(int argc, char *argv[]) {
std::cout << floor(std::numeric_limits<float>::quiet_NaN()) << std::endl;
std::cout << floor(std::numeric_limits<float>::infinity()) << std::endl;
std::cout << floor(-std::numeric_limits<float>::infinity()) << std::endl;
}
outputs
nan
inf
-inf
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