模数和余数的区别 [英] Difference between modulus and remainder

查看:199
本文介绍了模数和余数的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 javapython 中的 % 运算符进行一些计算.

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

问题

谁能用上面的例子简单解释一下modulusremainder的区别?

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) + 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

这篇关于模数和余数的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆