Python中对负数的取模运算

编程入门 行业动态 更新时间:2024-10-26 10:34:25
本文介绍了Python中对负数的取模运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在Python中发现了一些有关负数的奇怪行为:

I've found some strange behaviour in Python regarding negative numbers:

>>> -5 % 4 3

谁能解释发生了什么事?

Could anyone explain what's going on?

推荐答案

与C或C ++不同,Python的模运算符(%)始终返回与分母(除数)符号相同的数字.您的表情之所以产生3,是因为

Unlike C or C++, Python's modulo operator (%) always return a number having the same sign as the denominator (divisor). Your expression yields 3 because

(-5)/4 = -1.25->下限(-1.25)= -2

(-5) / 4 = -1.25 --> floor(-1.25) = -2

(-5)%4 =(-2× 4 + 3)%4 = 3.

(-5) % 4 = (-2 × 4 + 3) % 4 = 3.

选择它来代替C行为,因为非负结果通常更有用.一个示例是计算工作日.如果今天是星期二(第2天),那么前 N 天是星期几?在Python中,我们可以使用

It is chosen over the C behavior because a nonnegative result is often more useful. An example is to compute week days. If today is Tuesday (day #2), what is the week day N days before? In Python we can compute with

return (2 - N) % 7

但是在C中,如果 N ≥3,我们得到一个负数,它是无效数字,我们需要通过添加7来手动对其进行修正:

but in C, if N ≥ 3, we get a negative number which is an invalid number, and we need to manually fix it up by adding 7:

int result = (2 - N) % 7; return result < 0 ? result + 7 : result;

(请参阅 en.wikipedia/wiki/Modulo_operator 确定了不同语言的结果符号.)

(See en.wikipedia/wiki/Modulo_operator for how the sign of result is determined for different languages.)

更多推荐

Python中对负数的取模运算

本文发布于:2023-10-24 08:57:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1523503.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:负数   中对   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!