【问题标题】:Strange method result using Math.round使用 Math.round 的奇怪方法结果
【发布时间】:2013-12-18 09:58:44
【问题描述】:

当这个方法被调用时 knownScore = 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! 有什么帮助吗?

【问题讨论】:

标签: javascript methods return


【解决方案1】:

您传递给函数的 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

【讨论】:

  • 想知道depth 也不能是数字。
  • @raina77ow 结果与 newScore(可能还有 knownScore)是字符串而不是数字一致。如果 depth 也是一个字符串,则除法将产生与 3535 不同的数字。
【解决方案2】:

您需要像这样将 var 解析为数字:

var number1 = Number(n);

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

【讨论】:

  • 谢谢!在别处这样做是为了确保传递的参数是数字。
猜你喜欢
  • 1970-01-01
  • 2014-08-17
  • 2019-05-24
  • 1970-01-01
  • 1970-01-01
  • 2010-09-14
  • 2011-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多