获取两个数字之间的数字JavaScript

时间:2017-12-14 10:08:17

标签: javascript math

如何在两个数字之间的中获取number

例如:

var start = 0;
var end = 100;
var inBetween = 50;

就我而言,它将是:

var start = -122.0842499;
var end = 5.6366264;
var inBetween = "How do I get the exact number in between start and end?";

我尝试过关注,但返回的号码不正确。

var start = -122.0842499;
var end = 5.6366264;
var inBetween = start + end / 2;

console.log(inBetween) // Outputs -119.2659367

3 个答案:

答案 0 :(得分:3)

由于它是经度和纬度,(a+b)/2不正确。地球不平坦。

//-- Define radius function
if (typeof (Number.prototype.toRad) === "undefined") {
    Number.prototype.toRad = function () {
        return this * Math.PI / 180;
    }
}

//-- Define degrees function
if (typeof (Number.prototype.toDeg) === "undefined") {
    Number.prototype.toDeg = function () {
        return this * (180 / Math.PI);
    }
}


function middlePoint(lat1, lng1, lat2, lng2) {

    //-- Longitude difference
    var dLng = (lng2 - lng1).toRad();

    //-- Convert to radians
    lat1 = lat1.toRad();
    lat2 = lat2.toRad();
    lng1 = lng1.toRad();

    var bX = Math.cos(lat2) * Math.cos(dLng);
    var bY = Math.cos(lat2) * Math.sin(dLng);
    var lat3 = Math.atan2(Math.sin(lat1) + Math.sin(lat2), Math.sqrt((Math.cos(lat1) + bX) * (Math.cos(lat1) + bX) + bY * bY));
    var lng3 = lng1 + Math.atan2(bY, Math.cos(lat1) + bX);

    //-- Return result
    return [lng3.toDeg(), lat3.toDeg()];
}

取自http://jsfiddle.net/kevinrignault/gzq64p56/

答案 1 :(得分:1)

您正在寻找两个数字的方法,即

var start = -122.0842499;
var end = 5.6366264;
var inBetween = (start + end) / 2;

话虽如此,如果你真的在使用坐标,那么正确的方法就是@emil的答案。

答案 2 :(得分:1)



var start = -122.0842499;
var end = 5.6366264;
var inBetween = (start+end)/2
console.log(inBetween)