Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

% 符号的 mod 取模和 rem 取余 #49

Open
lovelmh13 opened this issue Nov 1, 2020 · 0 comments
Open

% 符号的 mod 取模和 rem 取余 #49

lovelmh13 opened this issue Nov 1, 2020 · 0 comments

Comments

@lovelmh13
Copy link
Owner

lovelmh13 commented Nov 1, 2020

1 对 4取模,是 1 % 4

不同语言中的 % 结果不一样

之所以不一样,是因为有的语言中,% 进行的是取模,有的是取余。

在C/C++, C#, JAVA, PHP, javaScript 这几门主流语言中,’%’运算符都是做取余运算,而在python中的’%’是做取模运算。

两者的不同,体现在对于商的处理
x / y = n....余数

mod取模

模 = x - n * y
mod时,商会向负无穷的方向取整。

通俗一点的例子:
mod(10, -3) -> n = 10/-3 = -3.333333333, 进行向下取整,n = -4
模 = 10 - (-4)*(-3) = -2

mod(10, 3) -> n = 10/3 = 3.333333333, 进行向下取整,n = 3
模 = 10 - (3)*(3) = 1

mod(-10, 3) -> n = -10/3 = -3.333333333, 进行向下取整,n = -4
模 = -10 - (-4)*(3) = 2

mod(-10, -3) -> n = -10/-3 = 3.333333333, 进行向下取整,n = 3
模 = -10 - (3)*(-3) = -1

可见,模的正负,取决于y值的正负

rem取余

余 = x - n * y,公式都是一样的
rem时,商会向0的方向取整。

通俗一点的例子:
rem(10, -3) -> n = 10/-3 = -3.333333333, 向0的方向取整,n = -3
余数 = 10 - (-3)*(-3) = 1

mod(10, 3) -> n = 10/3 = 3.333333333, 向0的方向取整,n = 3
余数 = 10 - (3)*(3) = 1

余数的正负,取决于x值的正负

用处

比如分库分表、取余数

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant