问题描述
我正在使用 java
和 python
中的 %
运算符进行一些计算.
I am doing some calculations with %
operator in java
and python
.
在进行计算时,我发现 %
运算符在处理负数时在两种语言中的工作方式不同.
While doing calculations, i found out that %
operator works differently in both languages when dealing with negative numbers.
例如
-21 % 4 = -1 // Java
-21 % 4 = 3 # Python
所以我查看了一些关于 stackoverflow 的帖子,发现在 java
中,%
给出了 remainder 而在 中python
, %
给出模.它们对于正数是相同的,但对于负数给出不同的结果,如上例所示.
so i looked at some of the posts here on stackoverflow and found out that in java
, %
gives remainder whereas in python
, %
gives modulus. They both are same for positive numbers but give different result in case of negative numbers as shown in example above.
所以我搜索了模数和余数之间的区别,在网上阅读了一些帖子,但我仍然不清楚余数和模数之间的区别
So i searched for the difference between modulus and remainder, read some posts online but difference between remainder and modulus is still not clear to me
问题
谁能用上面的例子简单解释一下modulus
和remainder
的区别?
Can someone explain the difference between modulus
and remainder
in simple terms using above example?
推荐答案
模运算符的实现在 Python 和 Java 等语言中是不同的.
The implementation of the modulo operator is different in Python and languages like Java.
在 Java 中,结果具有被除数的符号,但在 Python 中,符号来自除数.
In Java, the result has the sign of the dividend, but in Python, the sign is from the divisor.
要在 Java 中实现 Python 的结果,您可以使用:
To achieve the Python’s result in Java, you can use:
(((n % m) + m) % m)
其中 n 是被除数,m 是除数.
where n is the dividend and m – the divisor.
int a = (((-21% 4) + 4) % 4);
System.out.println(a); //a=3
这篇关于模数和余数的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!