C++ ceil and negative zero

寵の児 提交于 2019-12-10 07:17:34

问题


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.


回答1:


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.




回答2:


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.)




回答3:


I can't say that I know that it is usual, but as for avoiding printing it, implement a check, something like this:

if(var == -0.0)
{
    var = 0.0;
}
// continue



回答4:


Yes this is usual.

int number = (int) ceil(-0.5);

number will be 0




回答5:


I see why ceil(-0.5) is returning -0.0. It's because for negative numbers, ceil is returning the integer part of the operand:

double af8IntPart;
double af8FracPart = modf(-0.5, & af8IntPart);
cout << af8IntPart;

The output here is "-0.0"



来源:https://stackoverflow.com/questions/5986875/c-ceil-and-negative-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!