gpt4 book ai didi

python-2.7 - 为什么在 Python 中 (5 % 2) 和 (-5 % 2) 都是一样的

转载 作者:行者123 更新时间:2023-12-04 01:40:11 27 4
gpt4 key购买 nike

我猜 5 % 2 是 1 ,-5 % 2 是 -1

但是,在 Python 中,我得到了相同的结果。

我认为这不是数学问题。

>>> -5 % 2 
1 ( I think this should be -1 )
>>> 5 % 2
1

>>> -7 % 6
5 ( I think this should be -1 )
>>> 7 % 6
1

最佳答案

为什么?因为模运算符在 python 中是这样定义的。

documentation状态:

The modulo operator always yields a result with the same sign as its second operand (or zero); [...]



和:

The function math.fmod() returns a result whose sign matches the sign of the first argument instead, [...] Which approach is more appropriate depends on the application.

关于python-2.7 - 为什么在 Python 中 (5 % 2) 和 (-5 % 2) 都是一样的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45809408/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com