Java:为什么 7/-3 是 -2?

标签 java division

为什么在 java 7/-3 中不是 -3?它是-2。我在想除法的结果是四舍五入的。在 python 2 中它是 -3。 java除法还有其他规则吗?

最佳答案

Is there any other rule for division in java?

与往常一样,对于此类问题,您应该转到 Java Language Specification .在这种情况下,相关部分是 15.17.2 :

Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d ⋅ q| ≤ |n|. Moreover, q is positive when |n| ≥ |d| and n and d have the same sign, but q is negative when |n| ≥ |d| and n and d have opposite signs.

请注意,此“舍入”不是您可能期望的“中点舍入”:例如,-99/50 是 -1。实际上它是 截断 到 0。

至于为什么 Java 选择使用这种方法而 Python 选择取而代之,这可能是您需要询问语言设计者的问题。每个选项在某些情况下都很有用,而在其他情况下则很痛苦。您可能会发现余数运算符在 Python 中的工作方式也不同——这两个决定通常是相关联的,例如(来自 15.17.3 部分):

The remainder operation for operands that are integers after binary numeric promotion (§5.6.2) produces a result value such that (a/b)*b+(a%b) is equal to a.

关于Java:为什么 7/-3 是 -2?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26190848/

相关文章:

java - 在Java中,如果我的集合是只读的,我是否需要声明我的集合是同步的?

python - pandas 列划分 ValueError (putmask : mask and data must be the same size)

java - 准备好的语句从数据库填充列表

java - 插入sqlite中的自动增量列

java - 泽西客户端创建错误

Java - 维护对象集合的顺序

python - python 中变量的 float 除法错误

c++ - 给定输入序列,double_price 到 int_price 的更快版本

swift - Swift 中意外的除法结果

algorithm - 师大O