距离函数返回错误的东西

Distance function Returning the wrong thing

一段时间以来,我一直在尝试编写一个可以计算两点之间距离的函数。我使用这个网站:http://www.mathwarehouse.com/calculators/distance-formula-calculator.php 来查找公式,但它保留了 returning 不同的数字。从这个角度来看,该网站说 (0,0) 和 (50,100) 的距离是 111.80339887498948,而我的电脑说是 7.483314773547883。我很确定该网站是正确的,但我已经尝试了很多算法,但无法将其设置为 return 与该网站所做的相同。这是我的代码:

var distance = function(x1, y1, x2, y2) {
    var a = x2 - x1;
    a ^= 2;
    var b = y2 - y1;
    b ^= 2;
    var c = a + b;
    return Math.sqrt(c);
};

你能告诉我为什么这是在说错话吗?

^ 是 JavaScript 中的 bitwise XOR 运算符,因此 ^= 2 没有按照您的预期进行。

你想要的exponential operator (**) exists in ES2016, but unless you are using a transpiler it might not have the browser compatibility

几个备选方案:

乘法

var distance = function (x1, y1, x2, y2) {
  var dx = x2 - x1;
  var dy = y2 - y1;

  return Math.sqrt(dx*dx + dy*dy);
}

使用Math.pow

var distance = function (x1, y1, x2, y2) {
  var dx = x2 - x1;
  var dy = y2 - y1;

  return Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
}

使用exponential operator

var distance = function (x1, y1, x2, y2) {    
  return Math.sqrt(dx**2 + dy**2);
}

你应该使用 Math.pow 来使用指数:

function distance(x1, y1, x2, y2) {
    var a = Math.pow(x2 - x1, 2);
    var b = Math.pow(y2 - y1, 2);
    return Math.sqrt(a + b);
};

console.log(distance(0,0,0,50))