带负数的Mod在Java和C中给出否定结果 [英] Mod with negative numbers gives a negative result in Java and C
本文介绍了带负数的Mod在Java和C中给出否定结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有( - 5)mod 8
。
我用两种语言Java和C,当我期待 3
时,他们给了我 -5
的结果。
I tried it in both languages Java and C, and they gave me a -5
result when I was expecting 3
.
为什么会这样?模数可以为负数吗?我应该改变什么来获得正确的结果?
Why is this happening? Can a modulus be negative? And what should I change to get the correct result?
Java代码
public class Example {
public static void main(String[] args) {
int x;
x = -5%8;
System.out.println(x);
}
}
C代码
int main(){
int x;
x = -5%8;
printf("%d", x);
}
输出
推荐答案
%
运算符被视为余数运算符,因此结果的符号与被除数的符号相同。
The %
operator is treated as a remainder operator, so the sign of the result is the same as that of the dividend.
如果你想要模数函数,你可以这样做:
If you want a modulo function, you can do something like this:
int mod(int a, int b)
{
int ret = a % b;
if (ret < 0)
ret += b;
return ret;
}
这篇关于带负数的Mod在Java和C中给出否定结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文