使用Math.round的奇怪方法结果

Strange method result using Math.round

本文关键字:方法 结果 Math round 使用      更新时间:2024-02-02

当使用已知核心=70,newScore=70,深度=1,它返回3535!!!!!这怎么可能?

this.weightedAvg = function(depth, knownScore, newScore) {
   if ((knownScore > 100) || (knownScore < -100)) return newScore;
   else return Math.round((depth*knownScore + newScore)/(depth + 1));
};

当使用值35、70、2调用时,它将返回2357!请帮忙吗?

传递给函数的newScore值是一个字符串。你应该确保它们都是数字。此代码将起作用(注意将newScore转换为数字的+号):

this.weightedAvg = function(depth, knownScore, newScore) {
    if ((knownScore > 100) || (knownScore < -100)) return newScore;
    else return Math.round((depth*knownScore + +newScore)/(depth + 1));
};

更多详细信息:

70 + '70' // this is string concatenation instead of addition, results in 7070

当结果除以2:时,将其转换为数字

'7070'/2 // converts to number, resulting in 3535

您需要将var解析为如下数字:

var number1 = Number(n);

你正在传递字符串,所以他做"2"+"35"+"70"而不是2+35+70!