余数运算符的等效操作,用于处理低于允许的最小值

Equivalent operation to remainder operator for handling values below the minimal allowed

本文关键字:处理 于允许 用于 最小值 操作 运算符 余数      更新时间:2023-10-16

我在从0到5的循环中有一组索引。如果用户指定的索引大于 5,例如 7,则应返回索引 7-6=1。如果指定的索引低于 0,例如 -2,则应返回索引 -2+6=4。

在第一种情况下,我们可以使用余数运算符来处理上面的值 5:

int inputValue = 7;
int result = inputValue%6;

但是,是否有类似的操作来优雅地处理指定的索引低于 0 的情况?一个黑客的解决方案是:

if (inputValue < 0)
result = inputValue+6;
else
result = inputValue;

这仅处理大于或等于 -6 的值

如果你将负数修改为 6,你会得到一个负数,但你可以只加 6 得到你的正余数:

int result = (inputValue % 6) + (inputValue < 0? 6 : 0);

或者,使用将 6 加到正余数的事实会留下具有相同余数的数字:

int result = ((inputValue % 6) + 6) % 6;

希望这有帮助!