[英]My Javascript AVG Calculator doesn't work. How can i fix?
我想创建一个 function 来计算一些数字之间的平均值。 我想让我可以在 console.log 中输入任意数量的数字,但是这段代码显然不起作用,当我在 console.log 中显示“无穷大”时。 需要帮助请
function avg(...args){
return args.reduce(function (a, b) {
return a + b / avg.length
})
}
console.log(avg(1, 2, 3, 4, 5))
这是因为变量avg
不存在,它会默认为 0。导致它为Infinity
。
你还有 2 个额外的错误。
你没有使用括号,你实际上是在做a + ( b / len )
这将导致错误的答案
您使用的平均值公式不正确,在您使用的实现中,您应该使用运行平均值公式:请参阅此处: How to calculate moving average without keeping the count and data-total?
这将是正确的解决方案:
function avg(...args) {
const sum = args.reduce((a,b) => a + b , 0 );
return sum / args.length;
}
您可以像这样使用 reduce 和 arguments 长度。 您的代码中有一些错误。
const average = (...args) => args.reduce((a, b) => a + b) / args.length; console.log(average(1,2,3,4))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.