简体   繁体   English

我的 Javascript AVG 计算器不工作。 我该如何解决?

[英]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 个额外的错误。

  1. You have not used parenthesis, you are essentially doing a + ( b / len ) which will lead to an incorrect answer你没有使用括号,你实际上是在做a + ( b / len )这将导致错误的答案

  2. 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.

相关问题 我的 JavaScript 不起作用。 我怎么解决这个问题? - My JavaScript doesn't work. How can I solve this problem? 表中 Javascript 的动画不起作用。 怎么修? - Animation from Javascript in table doesn't work. How to fix? React-router 不起作用。 我该如何解决? - React-router doesn't work. How can i fix it? 我无法处理JavaScript冲突。 您应该如何检查它们? - I can't get my JavaScript collisions to work. How should you check for them? 正则表达式不起作用。 我的代码有什么问题? 谁能帮我解决这个问题 - Regex doesn't work. What's wrong with my code? Can anyone help me fix this 我的Javascript不起作用。不知道它是函数,我是如何调用它,我使用的CSS或者是什么 - My Javascript doesn't work. Don't know if it's the Function, how I'm calling it, the CSS I used or what Javascript Jquery不起作用。 $(本) - Javascript Jquery doesn't work. $(this) JavaScript代码不起作用。 为什么? - Javascript code doesn't work. Why? 我无法在 javascript 中显示计算器的结果,代码的 rest 不起作用 - I can't display the result of a calculator in javascript, the rest of the code doesn't work 清除间隔不起作用。 问题是什么? 我该如何解决? - ClearInterval doesn't work. What is the problem? How can I solve it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM