简体   繁体   English

为什么这段代码导致无限循环?

[英]Why does this code result in an infinite loop?

I cant for my life figure out why this doesn't work. 我不知道为什么这不起作用。

var refP = [];
var distance = function (p1, p2) {
    return dist(p1.x, p1.y, p2.x, p2.y);
}
while (refP.length < 24) {
    var pusher = {
        x: -1,
        y: -1,
        closestRefP: 9999999
    };
    pusher.x = (random(0, 400));
    pusher.y = (random(0, 400));
    for (var d = 0; d < refP.length; d++) {
        if (distance(pusher, refP[d]) < pusher.closestRefP) {
            pusher.closestRefP = distance(pusher, refP[d]);
        }
    }
    if (pusher.closestRefP > 2) {
        refP[refP.length] = pusher;
    }
}

It doesn't give me the loop when I remove the last if-statement and just unconditionally push pusher onto refP. 当我删除最后一个if语句并且无条件地将推送器推送到refP时,它不会给我循环。

Thanks. 谢谢。 And please let me know if I should clean up this code or maybe try to isolate the problem in less code. 如果我应该清理这些代码或者尝试用更少的代码来隔离问题,请告诉我。

Are you sure your random and dist functions works properly? 你确定你的randomdist功能正常吗?

Replacing your distance function with: 用以下代替你的distance函数:

var distance = function (point1, point2) {
  var xs = 0;
  var ys = 0;

  xs = point2.x - point1.x;
  xs = xs * xs;

  ys = point2.y - point1.y;
  ys = ys * ys;

  return Math.sqrt( xs + ys );
}

and your random(0, 400) calls with this: 和你的random(0, 400)调用:

pusher.x = Math.floor(Math.random() * 400);
pusher.y = Math.floor(Math.random() * 400);

Worked for me. 为我工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM