Why Math.Ceiling returns double?

后端 未结 5 1744
被撕碎了的回忆
被撕碎了的回忆 2021-01-07 15:52

In C# the method Math.Ceiling returns a double value. Why does it not return int?

相关标签:
5条回答
  • 2021-01-07 16:38

    double has a greater value range than int:

    The Double value type represents a double-precision 64-bit number with values ranging from negative 1.79769313486232e308 to positive 1.79769313486232e308, as well as positive or negative zero, PositiveInfinity, NegativeInfinity, and Not-a-Number (NaN).

    Double complies with the IEC 60559:1989 (IEEE 754) standard for binary floating-point arithmetic.

    That standard says that double has a 52-bit mantissa, which means it can represent any integer up to 52 bits long without loss of precision.

    Therefore if the input is large enough, the output doesn't fit inside an int (which only has 32 bits).

    0 讨论(0)
  • 2021-01-07 16:43

    It has to return double in order to be complete. Any math operation involving a NaN always returns NaN. Thus if you pass a NaN to ceiling() function one would not be able to return NaN, as there is no equivalent in Int. Also given that Double has a wider range what would one return for those out of range integer values ? What does one return for +/- inf ?

    0 讨论(0)
  • 2021-01-07 16:49

    The documentation says about the return value:

    The smallest whole number greater than or equal to a. If a is equal to NaN, NegativeInfinity, or PositiveInfinity, that value is returned.

    Therefore the return value has to be double since NaN, NegativeInfinity and PositiveInfinity are fields of Double.

    0 讨论(0)
  • 2021-01-07 16:55

    Because double can contain larger numbers than int or long. Same reason there's no implicit cast from double to int.

    0 讨论(0)
  • 2021-01-07 16:57

    Math.Ceiling can return either a double or a decimal, depending on the type passed in. In other words, the output type of the method matches the input type (quite sensibly).

    They could have added a third overload that takes an int and returns an int, but there wouldn't have been much point to this - the function would always just return its input.

    You seem to be assuming that the purpose of Math.Ceiling is to cast a floating-point value to an integer, but that's usually not how it's used.

    0 讨论(0)
提交回复
热议问题