为什么在 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
andd
that are integers after binary numeric promotion (§5.6.2) is an integer valueq
whose magnitude is as large as possible while satisfying|d ⋅ q| ≤ |n|
. Moreover, q is positive when|n| ≥ |d|
andn
andd
have the same sign, butq
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 toa
.
关于Java:为什么 7/-3 是 -2?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26190848/