2013-05-25 95 views
0

我不能爲我的生活找出爲什麼這不起作用。爲什麼此代碼導致無限循環?

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; 
    } 
} 

當我刪除最後一條if語句並且無條件地將推送器推送到refP時,它不會給我循環。

謝謝。請讓我知道是否應該清理此代碼,或者嘗試用較少的代碼隔離問題。

+0

是的,你應該嘗試更多的第一個問題。例如,你確定'pusher.closestRefP> 2'確實是真的嗎? – Matt

+0

最後refP if,使得refp <24因此是循環。 – JonathanRomer

回答

2

您確定您的randomdist功能正常嗎?

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); 
} 

和您的通話random(0, 400)此:

與更換您的distance功能

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

爲我工作。

+0

我的編輯似乎沒有接受這段代碼,但是當我把它放到另一個編輯器中時,它肯定會起作用。我想是時候改變編輯。謝謝! – Henrik

+0

您正在使用什麼編輯器,它在抱怨什麼? – rtcherry

+0

我在khanacademy的編輯工作。昨天我設法設置了Textmate。 (我在Mac上) – Henrik

相關問題