整数除法在Python中使用负操作数进行模运算 [英] Integer division & modulo operation with negative operands in Python

查看:60
本文介绍了整数除法在Python中使用负操作数进行模运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在Python 3.3.0中键入这些表达式时会出现问题

Questions arise when I type in these expressions to Python 3.3.0

-10 // 3  # -4
-10 % 3   #  2
10 // -3  # -4
10 % -3   # -2
-10 // -3 #  3

好像需要大约浮点数(-3.33)?并在整数除法中四舍五入,但是在取模运算中它做的事情完全不同.似乎它返回余数+/- 1并仅根据负操作数所在的位置切换符号.即使在查看本网站上的其他答案之后,我也完全感到困惑!我希望有人也能清楚地解释这一点!这本书说出了一些提示:回想一下这个神奇的公式a =(a//b)(b)+(a%b),但这似乎并没有为我清除一切.

It appears as though it takes the approximate floating point (-3.33)? and rounds down either way in integer division but in the modulo operation it does something totally different. It seems like it returns the remainder +/-1 and only switches the sign depending on where the negative operand is. I am utterly confused, even after looking over other answers on this site! I hope someone can clearly explain this too me! The book says hint: recall this magic formula a = (a//b)(b)+(a%b) but that doesn't seem to clear the water for me at all.

-提前谢谢!

编辑:这些只是我对上述情况的个人评估,我知道,我已经完全放弃了!

Those are just my personal assessments of what happens (above), I know, I'm completely off!

推荐答案

那里的整数除法只是占据了最后获得的数字的底数.

The integer division there is just taking the floor of the number obtained at the end.

10/3  -> floor(3.33)  ->  3
-10/3 -> floor(-3.33) -> -4

(为什么落空)

(Why it floors)

另一方面,模运算遵循 数学定义 .

The modulo operation on the other hand is following the mathematical definition.

这篇关于整数除法在Python中使用负操作数进行模运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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