29

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?

Omnifarious
  • 54,333
  • 19
  • 131
  • 194
danijar
  • 32,406
  • 45
  • 166
  • 297

1 Answers1

56

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
Lily Ballard
  • 182,031
  • 33
  • 381
  • 347