On VC++ 2008, ceil(-0.5)
is returning -0.0
. Is this usual/expected behavior? What is the best practice to avoid printing a -0.0
to i/o streams.
ceil function. (Ceiling) In the C Programming Language, the ceil function returns the smallest integer that is greater than or equal to x (ie: rounds up the nearest integer).
Still, for a real number ( float or double) in C, it’s theoretically possible to have a positive or negative value of zero. The question is whether the C language recognizes the difference. In the following code, I use the sign operator to compare the values zero, positive zero, and negative zero.
The C library function double ceil(double x) returns the smallest integer value greater than or equal to x.
Negatively signed zero echoes the mathematical analysis concept of approaching 0 from below as a one-sided limit, which may be denoted by x → 0−, x → 0−, or x → ↑0. The notation "−0" may be used informally to denote a small negative number that has been rounded to zero.
ceil
in C++ comes from the C standard library.
The C standard says that if a platform implements IEEE-754 arithmetic, ceil( )
behaves as though its argument were rounded to integral according to the IEEE-754 roundTowardPositive rounding attribute. The IEEE-754 standard says (clause 6.3):
the sign of the result of conversions, the quantize operation, the roundToIntegral operations, and the roundToIntegralExact is the sign of the first or only operand.
So the sign of the result should always match the sign of the input. For inputs in the range (-1,0)
, this means that the result should be -0.0
.
This is correct behavior. See Unary Operator-() on zero values - c++ and http://en.wikipedia.org/wiki/Signed_zero
I am partial to doing a static_cast<int>(ceil(-0.5));
but I don't claim that is "best practice".
Edit: You could of course cast to whatever integral type was appropriate (uint64_t, long, etc.)
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