java如何用负数进行模数计算? [英] How does java do modulus calculations with negative numbers?

查看:167
本文介绍了java如何用负数进行模数计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做模数错了吗?因为在Java -13%64 应该评估为 -13 但我得到 51

Am I doing modulus wrong? Because in Java -13 % 64 is supposed to evaluate to -13 but I get 51.

推荐答案

负数模数的两个定义都在使用中 - 某些语言使用一个定义和其他一些。

Both definitions of modulus of negative numbers are in use - some languages use one definition and some the other.

如果你想获得负数输入的负数,那么你可以使用它:

If you want to get a negative number for negative inputs then you can use this:

int r = x % n;
if (r > 0 && x < 0)
{
    r -= n;
}

同样,如果您使用的语言在负输入上返回负数你更喜欢积极的:

Likewise if you were using a language that returns a negative number on a negative input and you would prefer positive:

int r = x % n;
if (r < 0)
{
    r += n;
}

这篇关于java如何用负数进行模数计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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