变量值固定为0(内部函数)

时间:2018-07-17 07:58:07

标签: javascript

computeDistance 函数内部,无论参数值如何,x,y和dist的值始终始终为0。

function computeDistance(loA, laA, loB, laB) {
    var dist = 0;
    printErr("++++Parameters inside computeDistance: loA, laA, loB, laB");
    printErr("++++Parameters inside computeDistance:", loA, laA, loB, laB);

    var x = (loB - loA) * Math.cos( (laA + laB) / 2 );
    printErr("++++Inside computeDistance, x=",x);
    var y = (laB - laA);
    printErr("++++Inside computeDistance, y=",y);
    dist = Math.sqrt(Math.pow(x,2) + Math.pow(y,2)) * 6371

    return dist;
}

以下是调用和输出的示例:

++++Parameters inside computeDistance: loA, laA, loB, laB
++++Parameters inside computeDistance: 0.05235987755982988 0.7504915783575616 0.05235987755982988 0.7504915783575616
++++Inside computeDistance, x= 0
++++Inside computeDistance, y= 0

为什么 x y 值固定为0?

2 个答案:

答案 0 :(得分:2)

@Elliad因为您要输入相同的loB,loA值,并且显然会返回0。 请检查输入内容

loA :  0.05235987755982988
loB : 0.05235987755982988

loB- loA = 0

答案 1 :(得分:1)

因为loB-输入的loA始终为0,而​​laB和laA也相等,所以

x = (loB - loA) **is 0**

y = (laB - laA) **is also 0**

交换您的输入参数。您肯定会得到一些东西

function computeDistance(loA, laA, loB, laB) {

    var dist = 0;
    console.log("++++Parameters inside computeDistance: loA, laA, loB, laB");
    console.log("++++Parameters inside computeDistance:", loA, laA, loB, laB);

    var x = (loB - loA) * Math.cos( (laA + laB) / 2 );
    console.log("++++Inside computeDistance, x=",x);
    var y = (laB - laA);
    console.log("++++Inside computeDistance, y=",y);
    dist = Math.sqrt(Math.pow(x,2) + Math.pow(y,2)) * 6371

    return dist;
}

console.log(computeDistance(0.7504915783575616,0.05235987755982988, 0.05235987755982988,0.7504915783575616));