C++ 与 python 整数除法差异

-1/20=?

 

C++ 里面结果是         0

Python 里面结果是     -1

 

Python里面的注意事项里面,也提到了这点“总是向负无穷取整”

For (plain or long) integer division, the result is an integer. The result is always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result is a long integer if either operand is a long integer, regardless of the numeric value.

 

C++ 里面也想得到这样的结果,就必须把整形的除法转换为浮点数的除法,然后对结果取 floor。

static_cast<int>(floor(static_cast<double>(-1)/20)  )

 

posted on 2012-02-16 14:09  JesseFang  阅读(522)  评论(0编辑  收藏  举报