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

 

相关文章:

  • 2022-12-23
  • 2021-12-19
  • 2021-06-12
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-24
猜你喜欢
  • 2021-08-28
  • 2022-02-02
  • 2022-12-23
  • 2021-06-19
  • 2022-01-18
  • 2021-12-21
  • 2022-12-23
相关资源
相似解决方案