当这个方法被调用时 已知分数 = 70, 新分数 = 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
关于javascript - 使用 Math.round 的奇怪方法结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20332611/