如何使负数的mod变为正数?

Hai*_*ang 20 c++

基本上,我需要(-3) % 5是"2"而不是"-3".Python产生"2",但C++产生"-3".不知道如何在C++中生成"2".谢谢!

yst*_*sth 21

((x % 5) + 5) % 5 但我确信这是一种更优雅的方式.


Qwe*_*tie 6

The quick & dirty way is to write

((x % divisor) + divisor) % divisor
Run Code Online (Sandbox Code Playgroud)

For example, ((-3 % 5) + 5) % 5 == 2. However this performs two separate divisions, and since divisions are one of the slowest arithmetic operations you might like one of these alternatives:

(1) General mod for integer or floating point

int mod(int x, int divisor)
{
    int m = x % divisor;
    return m + (m < 0 ? divisor : 0);
}

template<class Num> Num mod(Num x, Num divisor)
{
    Num m = x % divisor;
    return m + (m < 0 ? divisor : 0);
}
Run Code Online (Sandbox Code Playgroud)

(2) Non-branching mod for 32-bit integers

int mod(int x, int divisor)
{
    int m = x % divisor;
    return m + ((m >> 31) & divisor);
}
Run Code Online (Sandbox Code Playgroud)

All this assumes that the divisor is always positive.


per*_*eal 5

如果输入数字X为负,则添加基数:

X % Y + (X % Y < 0 ? Y : 0);
Run Code Online (Sandbox Code Playgroud)