java - 模数运算返回奇怪的结果

标签 java

该程序将一个数相除并计算其商和余数。但我得到了模数运算的奇怪结果。

public String operater(int arg1, int arg2) throws IllegalArgumentException
{
    int quotient;
    int remainder;
    String resString;

    // Check for Divide by 0 Error.
    if(arg2 == 0)
    {
        throw new IllegalArgumentException("Illegal Argument!");
    }
    else
    {
        quotient = arg1 / arg2;
        remainder = arg1 % arg2;
        resString = "Quotient: " + Integer.toString(quotient) + 
            Remainder: " + Integer.toString(remainder);
    }

    return resString;
}

58585/-45 给出的商为 -1301,余数为 40。但 Google 表示 58585 % -45 = -5。我认为原因是在做标志时有特殊的规则来处理标志。

来自Modulo Operations :

"However, this still leaves a sign ambiguity if the remainder is nonzero: two possible choices for the remainder occur, one negative and the other positive, and two possible choices for the quotient occur. Usually, in number theory, the positive remainder is always chosen, but programming languages choose depending on the language and the signs of a and/or n.[6] Standard Pascal and ALGOL 68 give a positive remainder (or 0) even for negative divisors, and some programming languages, such as C90, leave it to the implementation when either of n or a is negative. See the table for details. a modulo 0 is undefined in most systems, although some do define it as a."

我想修复我的程序,但是我不明白这意味着什么。

最佳答案

取决于你想要什么。在数学和某些编程语言中,如果模不为零,则它与除数具有相同的符号,将整数除法视为朝负无穷大截断。在其他编程语言中,如果模不为零,则它与被除数具有相同的符号,将整数除法视为向零截断。某些编程语言同时包含模运算符(符号与除数相同)和余数运算符(符号与被除数相同)。

对于数学类型的模,则 r = (a + k*b)%b 为 r 返回相同的值,无论 k 是负数、零还是正数。这也意味着任何模 b 的被除数只有 b 个可能的值,而不是其他情况,模 b 的被除数有 2*b - 1 个可能的值,具体取决于被除数的符号。

使模数按照数学中的方式工作的 C 示例:

int modulo(int n, int p)
{
int r = n%p;
    if(((p > 0) && (r < 0)) || ((p < 0) && (r > 0)))
        r += p;
    return r;
}

关于java - 模数运算返回奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39421724/

相关文章:

java - 用于 IntelliJ 多线程测试的 Java 工具

java - 未找到 JDK。请验证 STUDIO_JDK、JDK_HOME 或 JAVA_HOME 环境变量是否指向有效的 JDK 安装

java - 等到文本出现在文本字段中

java - 自定义控件内的 Android 微调器 - OnItemSelectedListener 不会触发

java - 无法使用 JDK 9.0.4 在 Netbeans 8.2 上创建项目

java - ArrayList,双包含

Java HttpSession .getAttribute(字符串名称)

java - 如何在 Android studio 中只执行一个选项卡的内容?

java - 令人惊讶的双重比较

java - Batik SVG 到 PDF - PDFTranscoder - 页面大小 A4