在不使用if语句的情况下递减值并回绕到最大值?

时间:2015-11-12 04:11:44

标签: c bit-manipulation bitwise-operators decrement

增加并回归到零很容易:

i = (i + 1) % Max;

但减量并不是那么直接。基本上减少和包装你通常会找到这样的代码:

i--;
if (i < 0)
   i = Max;

如何在不使用if语句的情况下编写前面的代码?

我知道可能涉及到逐位运算符。通常当我遇到这些问题时,我会尝试用两个术语A和B来提出一些方程式,然后尝试找出这两个术语的实际值。例如:

i = A + B

如果i]0, Max]范围内,那么我们就得到:

i = 0 + BB = i-1

否则如果i == 0

i = A + 0A = Max

同样我们可以写:

i = i == 0 ? Max : i - 1;

如何在没有任何ifs或三元运算符的情况下编写上一个等式?我尝试了很多按位操作和不同的算术组合,但无济于事。

有什么想法吗?

2 个答案:

答案 0 :(得分:4)

node = node.data(force.nodes(), function(d) { return d.id;})
    .enter().append("g")
    .attr("class", "node")
    .call(drag);

node.append("circle")
    .attr("r", 5)
    .style("fill", function(d) { return color(d.group); });

node.append("text")
    .attr("dx", 12)
    .attr("dy", ".35em")
    .text(function(d) { return d.name });
只要function tick() { link.attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); }

就会有效。

答案 1 :(得分:-1)

你可以修改它以适应你需要的范围

&#13;
&#13;
jquery
&#13;
document
&#13;
&#13;
&#13;