gpt4 book ai didi

java - 为什么这会返回错误的模数答案?

转载 作者:行者123 更新时间:2023-12-01 18:39:02 26 4
gpt4 key购买 nike

    private int mCurrentIndex = 0;
mPrevButton = (Button)findViewById(R.id.prev_button);
mPrevButton.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

mCurrentIndex = (-33 % 5);
Log.i("IndexClick", String.valueOf(mCurrentIndex));
}
});

这将返回 -3 而不是 2。它用正数进行正确的数学运算。请帮助似乎无法找到解决方案。

最佳答案

根据 JLS, Section 15.17.3,使用 % 运算符时,余数的符号必须与被除数的符号匹配(或者为 0)。 :

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.

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.

事实上,(-33/5)*5 + (-33%5) 变为 -6*5 + (-3) ,等于 -33.

要获得积极的结果,您必须获得积极的股息。

关于java - 为什么这会返回错误的模数答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20689074/

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