模数行为 -1 % 3 (C++)

csg*_*guy 0 c++ modulo

if (currIndex < 0) {

            cout << currIndex << " % " << array.size() << endl;

            currIndex = currIndex % array.size();

            cout << currIndex << endl;
}
Run Code Online (Sandbox Code Playgroud)

输出:

-1 % 3
0
Run Code Online (Sandbox Code Playgroud)

-1 % 3 = -1 在 C++ 中,为什么返回 0?

完整片段:https : //ideone.com/leWqhi

Mic*_*tin 6

size() 返回无符号整数类型,因此该计算是通过将 -1 转换为无符号并执行无符号模来完成的。

将 size() 转换为有符号整数类型以获得正确的结果。