[英]My Javascript AVG Calculator doesn't work. How can i fix?
I wanted to create a function that calculate the average between some numbers.我想创建一个 function 来计算一些数字之间的平均值。 I wanted to make it that i could put as many numbers as i wanted in the console.log but this code apparently doesn't work, when i console.log it says "infinity".
我想让我可以在 console.log 中输入任意数量的数字,但是这段代码显然不起作用,当我在 console.log 中显示“无穷大”时。 Need help please
需要帮助请
function avg(...args){
return args.reduce(function (a, b) {
return a + b / avg.length
})
}
console.log(avg(1, 2, 3, 4, 5))
This is because the variable avg
does not exist, and it will default to 0. Causing it to be Infinity
.这是因为变量
avg
不存在,它会默认为 0。导致它为Infinity
。
You also have 2 additional mistakes.你还有 2 个额外的错误。
You have not used parenthesis, you are essentially doing a + ( b / len )
which will lead to an incorrect answer你没有使用括号,你实际上是在做
a + ( b / len )
这将导致错误的答案
You are using incorrect formula for average, in the implementation that you are using, you should be using the running average formula: refer here: How to calculate moving average without keeping the count and data-total?您使用的平均值公式不正确,在您使用的实现中,您应该使用运行平均值公式:请参阅此处: How to calculate moving average without keeping the count and data-total?
this would be the correct solution:这将是正确的解决方案:
function avg(...args) {
const sum = args.reduce((a,b) => a + b , 0 );
return sum / args.length;
}
You can use reduce and arguments length like this.您可以像这样使用 reduce 和 arguments 长度。 You had some mistakes in your code.
您的代码中有一些错误。
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.