如何执行距离计算并获得在JavaScript中显示的答案?

时间:2013-03-08 21:10:19

标签: javascript computer-science

我无法弄清楚如何制作指导员给出的工作和显示和回答的公式。他给出的公式是:

distance = Math.sqrt( ( (x2-x1)*(x2-x1) ) + ( (y2-y1)*(y2-y1) ) );

2 个答案:

答案 0 :(得分:0)

它是(x2-x1)*(x2-x1),而不是(x2-x1)*(c2-x1)

答案 1 :(得分:0)

你的公式错了。正确的是:sqrt((x2 - x1)^ 2 +(y2 - y2)^ 2)

// Two points to find the distance between
var a = [564,426];
var b = [56,784];

// subtract the x's and square the result
var xN = Math.pow( b[0] - a[0], 2 );

// subtract the y's and square the result
var yN = Math.pow( b[1] - a[1], 2 );

// Add the two results together then find their square root
var distance = Math.sqrt(xN + yN);

资源:http://www.mathwarehouse.com/algebra/distance_formula/index.php