gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:09:45 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com