相关疑难解决方法(0)

Python中负数的模运算

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

>>> -5 % 4
3
Run Code Online (Sandbox Code Playgroud)

谁能解释一下发生了什么?

python modulo negative-number

64
推荐指数
6
解决办法
5万
查看次数

负数的模数

可能重复:
负数的Mod正在融化我的大脑!

我想知道是否有一个更好的算法,我正在尝试做什么:

wrapIndex(-6, 3) = 0
wrapIndex(-5, 3) = 1
wrapIndex(-4, 3) = 2
wrapIndex(-3, 3) = 0
wrapIndex(-2, 3) = 1
wrapIndex(-1, 3) = 2
wrapIndex(0, 3) = 0
wrapIndex(1, 3) = 1
wrapIndex(2, 3) = 2
wrapIndex(3, 3) = 0
wrapIndex(4, 3) = 1
wrapIndex(5, 3) = 2

我想出来了

function wrapIndex(i, i_max) {
        if(i > -1)
            return i%i_max;

        var x = i_max + i%i_max;
        if(x == i_max)
            return 0;

        return x;
    }

有没有更好的方法来做到这一点?

algorithm math modulo

18
推荐指数
3
解决办法
7283
查看次数

标签 统计

modulo ×2

algorithm ×1

math ×1

negative-number ×1

python ×1