简体   繁体   English

为什么余数(模数)除法返回负数

[英]why does remainder (modulus) division return negative numbers

    x=-10 % -4;
    System.out.println("-10% -4 : "+x); //-2 second row

The output '-2' why in the answer is a negative value? output '-2' 为什么在答案中是负值?

% is remainder division. % 是余数除法。 It is the amount left over after the integer division.这是 integer 除法后剩余的数量。

x = -10 / -4; // == 2

and

x = -10 % -4; // == -2

The later can be thought of as -10 divided by -4 (which is 2) with a remainder of -2.后者可以被认为是 -10 除以 -4(即 2),余数为 -2。

It might be easier to see if both answers were not the same absolute value.可能更容易看出两个答案的绝对值是否不同。

x = -10 / -3; // == 3

and

x = -10 % -3;  == -1

Unfortunately that is the way the Java modulus operator works with negative numbers.不幸的是,这就是 Java 模数运算符处理负数的方式。 If you want only positive remainder values then do a simple conversion like this:如果您只想要正余数,请执行如下简单转换:

if(x < 0){
    x = x * -1;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM