C++向上和负零
在 VC++ 2008 上,ceil(-0.5)
返回 -0.0
。这是通常/预期的行为吗?避免将 -0.0
打印到 i/o 流的最佳实践是什么。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
C++中的
ceil
来自C标准库。C 标准规定,如果平台实现 IEEE-754 算术,则
ceil( )
的行为就好像其参数根据 IEEE-754 roundTowardPositive 舍入属性舍入为整数。 IEEE-754 标准规定(第 6.3 条):因此结果的符号应始终与输入的符号匹配。对于
(-1,0)
范围内的输入,这意味着结果应为-0.0
。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):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
.这是正确的行为。请参阅零值上的一元运算符 - () - c++ 和 http://en.wikipedia.org/wiki/Signed_zero
我偏向于进行
static_cast< int>(ceil(-0.5));
但我并不认为这是“最佳实践”。编辑:您当然可以转换为任何合适的整数类型(uint64_t、long 等)
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.)
我不能说我知道这是常见的,但为了避免打印它,请实施检查,如下所示:
I can't say that I know that it is usual, but as for avoiding printing it, implement a check, something like this:
是的,这很平常。
数字将为 0
Yes this is usual.
number will be 0
我明白为什么
ceil(-0.5)
返回-0.0
。这是因为对于负数,ceil
返回操作数的整数部分:这里的输出是“-0.0”
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:The output here is "-0.0"