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

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

问题描述

当我计算 int i = -1%2 我在Java中得到 -1 。在Python中,由于 -1%2 ,我得到 1
我需要做些什么来使用模数函数在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天全站免登陆