gpt4 book ai didi

java - 为什么 4 % -8 等于 4?

转载 作者:行者123 更新时间:2023-12-03 11:17:15 26 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How does java do modulus calculations with negative numbers?

(14 个回答)


10 个月前关闭。




在 java ,

4 % -8
给出 4 作为输出而不是
-4
正如我所料。

最佳答案

这在 Java language specification section 15.17.3 中有详细介绍.

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

This identity holds even in the special case that the dividend is the negative integer of largest possible magnitude for its type and the divisor is -1 (the remainder is 0).

It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive. Moreover, the magnitude of the result is always less than the magnitude of the divisor.


因此,例如, -4 % 8确实是 -4 ,但由于 4/-80 , 和 0 * -8 == 0 , 余数 4 % -8必须是 4。

关于java - 为什么 4 % -8 等于 4?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64634834/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com