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

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

问题描述

我做模数错了吗?因为在 Java 中 -13 % 64 计算为 -13 但我想得到 51.

Am I doing modulus wrong? Because in Java -13 % 64 evaluates to -13 but I want to 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天全站免登陆