负数的模
可能的重复:
负数 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; }
Is there a better way to do this?
Possible Duplicate:
Mod of negative number is melting my brain!
I was wondering if there was a nicer algorithm for what I'm trying to do:
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
I came up with
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; }
Is there a nicer way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
该解决方案是无分支的,但执行
%
两次:应该说
%
的 C#/Java 行为是假定的,即结果与 具有相同的符号股息。某些语言将余数计算定义为取除数的符号(例如 Clojure 中的mod
)。有些语言同时具有这两种变体(Common Lisp、Haskell 等中的mod
/rem
对)。 Algol-68 的%x
始终返回非负数。 C++ 将其留给实现,直到 C++11,现在余数的符号是 (几乎)根据股息符号完全指定。另请参阅
This solution is branchless, but performs
%
twice:It should be said the C#/Java behavior of
%
is assumed, i.e. the result has the same sign as the dividend. Some languages define the remainder calculation to take the sign of the divisor instead (e.g.mod
in Clojure). Some languages have both variants (mod
/rem
pair in Common Lisp, Haskell, etc). Algol-68 has%x
which always returns a non-negative number. C++ left it up to implementation until C++11, now the sign of the remainder is (almost) fully specified according to the dividend sign.See also
使用两个
%
操作的解决方案是可行的,但是在大多数硬件上的大多数语言中,这会更快一些(但是也有例外):The solution with two
%
operations works, but this is somewhat faster in most languages on most hardware (there are exceptions, however):更好是一个品味问题,但是怎么样
Nicer is a matter of taste, but How about
你可以这样做:
You could do this:
许多用户给出了很好的答案,只是要小心负数,因为不同的语言可能会有不同的表现。
例如,这个 C 代码片段写的是“-1”,
而在 python 中我们有一个不同的输出值
编辑:实际上我不认为你会有负索引!不过,很高兴知道这一点。
Many users gave good answers, just beware negative numbers, since different languages may behave differently.
By example this C snippet writes "-1"
While in python we have a different output value
EDIT: Actually I don't think you'll have negative indexes! However it's good to know that.