Java中的Mod产生负数 [英] Mod in Java produces negative numbers

查看:32
本文介绍了Java中的Mod产生负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我计算 int i = -1 % 2 时,我在 Java 中得到 -1.在 Python 中,我得到 1 作为 -1 % 2 的结果.我该怎么做才能使用模函数在 Java 中获得相同的行为?

When I calculate int i = -1 % 2 I get -1 in Java. In Python, I get 1 as the result of -1 % 2. What do I have to do to get the same behavior in Java with the modulo function?

推荐答案

这里的问题是在 Python 中 % 运算符返回模数,而在 Java 中它返回余数.这些函数为正参数给出相同的值,但模数总是为负输入返回正结果,而余数可能给出负结果.这个问题中有更多相关信息.

The problem here is that in Python the % operator returns the modulus and in Java it returns the remainder. These functions give the same values for positive arguments, but the modulus always returns positive results for negative input, whereas the remainder may give negative results. There's some more information about it in this question.

您可以通过这样做找到正值:

You can find the positive value by doing this:

int i = (((-1 % 2) + 2) % 2)

或者这个:

int i = -1 % 2;
if (i<0) i += 2;

(显然 -1 或 2 可以是任何你想要的分子或分母)

(obviously -1 or 2 can be whatever you want the numerator or denominator to be)

这篇关于Java中的Mod产生负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆