如何修复我的问题,排除JavaScript中的0?

huangapple go评论52阅读模式
英文:

How do I fix my problem excluding 0s in my javascript?

问题

我正在尝试在我的平均数代码中排除0。该代码应该要求用户输入4个数字,然后输出它们的平均值。

这段代码运行正常,但现在我想从代码中排除0,它可以排除一个0,但如果你输入两个0就无法排除。我的想法是删除包含0的num,以便计算仅包含0>数字的平均值。以下是我的代码:

var num1 = parseInt(prompt("第一个数字:"), 10);
var num2 = parseInt(prompt("第二个数字:"), 10);
var num3 = parseInt(prompt("第三个数字:"), 10);
var num4 = parseInt(prompt("第四个数字:"), 10);

if (num1 == 0) {
    document.getElementById("output").textContent = ((num2 + num3 + num4) / 3);
}
if (num2 == 0) {
    document.getElementById("output").textContent = ((num1 + num3 + num4) / 3);
}
if (num3 == 0) {
    document.getElementById("output").textContent = ((num1 + num2 + num4) / 3);
}

if (num4 == 0) {
    document.getElementById("output").textContent = ((num1 + num2 + num3) / 3);
}
else {
    document.getElementById("output").textContent = ((num1 + num2 + num3 + num4) / 4);
}

注意:这段代码仅会排除一个0,如果要排除多个0,需要进行额外的逻辑处理。

英文:

I am trying to exclude 0 in my average code. The code is supposed to ask the user to write 4 numbers and then output an average between them 4.

The code works fine, but now I want to exclude 0s from the code, and it worked but only if you digit 0 one time. For example: I want to exclude two 0s but I have no idea how to do it. My idea was to delete the num that has 0 in it so the operation calculates the 0\> numbers only. There is my code:

var num1 = parseInt(prompt("first number: "),10);
var num2 = parseInt(prompt("second number: "),10);
var num3 = parseInt(prompt("third number: "),10);
var num4 = parseInt(prompt("fourth number: "),10);
  
  
if (num1==0){
    document.getElementById("output").textContent = ((num2 + num3+ num4) / 3);  
}
if (num2==0){
    document.getElementById("output").textContent = ((num1 + num3+ num4) / 3);  
}
if (num3==0){
    document.getElementById("output").textContent = ((num1 + num2+ num4) / 3);  
}
  
if (num4==0){
    document.getElementById("output").textContent = ((num1 + num2+ num3) / 3);  
}
else {
    document.getElementById("output").textContent = ((num1 + num2 + num3+ num4) / 4);  
}

答案1

得分: 2

以下是您要翻译的内容:

"Think about your current line of thought. You wrote some code that averages between 3 numbers if one of the 4 numbers is zero. Now you realize it doesn't work when 2 of the 4 numbers are zeroes. How many more if-elses would you need to write to accommodate that? Then imagine if 3 of them were zeroes.

This problem is pretty simple because you only take 4 inputs. Now imagine if you took 100 inputs and are trying to get averages of all the non-zero integers from there.

A much more scalable solution would be to have it be such that no matter how many inputs you take, the code will only look at and average the non-zero integers. Something like this:

let num1 = 3;
let num2 = 4;
let num3 = 0;
let num4 = 0;

const numbers = [num1, num2, num3, num4]

function avgNonZeroValues(nums){
  const nonZeros = nums.filter(number => number !== 0);
  const avgOfNonZeros = nonZeros.reduce(
    (accumulator, currentValue) => accumulator + currentValue,
    0
  )/nonZeros.length;

  return avgOfNonZeros;
}

console.log(avgNonZeroValues(numbers));

You need to know two functions:

  1. reduce()

Reduce is a very handy method to go through a list/array and do something with it. It takes in an initial value(0 for us), and we also tell it what to do with every element. Here, we are saying "keep on adding the elements. Here, we are using it to get the sum of all the numbers in the array.

  1. filter()

Filter is pretty self-explanatory. You give this function an array and a condition, and it will filter out the elements that do not satisfy the condition, and will give you a new array of all the elements that do satisfy the condition. Here, we are using it to filter all the zeros out of the array.

You give this function avgNonZeroValues an array of any length containing numbers, it will remove all the 0s and average the rest of them."

英文:

Think about your current line of thought.

You wrote some code that averages between 3 numbers if one of the 4 numbers is zero. Now you realize it doesn't work when 2 of the 4 numbers are zeroes. How many more if-elses would you need to write to accommodate that? Then imagine if 3 of them were zeroes.

This problem is pretty simple because you only take 4 inputs. Now imagine if you took 100 inputs and are trying to get averages of all the non-zero integers from there.

A much more scalable solution would be to have it be such that no matter how many inputs you take, the code will only look at and average the non-zero integers. Something like this:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let num1 = 3; //imagine it were equivalent to var num1 = parseInt(prompt(&quot;first number: &quot;),10);
let num2 = 4; //imagine it were equivalent to var num2 = parseInt(prompt(&quot;second number: &quot;),10);
let num3 = 0; //imagine it were equivalent to var num3 = parseInt(prompt(&quot;third number: &quot;),10);
let num4 = 0; //imagine it were equivalent to var num4 = parseInt(prompt(&quot;fourth number: &quot;),10);

const numbers = [num1, num2, num3, num4]

function avgNonZeroValues(nums){
  const nonZeros = nums.filter(number =&gt; number !== 0);
  const avgOfNonZeros = nonZeros.reduce(
    (accumulator, currentValue) =&gt; accumulator + currentValue,
    0
  )/nonZeros.length;
  
  return avgOfNonZeros;
}

console.log(avgNonZeroValues(numbers));

<!-- end snippet -->

You need to know two functions:

  1. reduce()

Reduce is a very handy method to go through a list/array and do something with it. It takes in a initial value(0 for us), and we also tell it what to do with every element. Here, we are saying "keep on adding the elements. Here, we are using it to get the sum of all the numbers in the array.

  1. filter()

Filter is pretty self-explanatory. You give this function an array and a condition, and it will filter out the elements that do not satisfy the condition, and will give you a new array of all the elements that do satisfy the condition. Here, we are using it to filter all the zeros out of the array.

You give this function avgNonZeroValues an array of any length containing numbers, it will remove all the 0s and average the rest of them.

答案2

得分: 0

重构此代码以使用数组,允许轻松使用数组函数来过滤和转换数字。

const prompts = ["first", "second", "third", "fourth"];

const values = prompts
  .map(p => parseInt(prompt(`${p} number: `), 10))
  .filter(v => v !== 0);

const total = values.reduce((acc, val) => acc + val, 0);
const avg = total / values.length;

console.log(total, avg);
英文:

Refactoring this to use arrays allows easy use of array functions to filter and transform the numbers.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const prompts = [&quot;first&quot;, &quot;second&quot;, &quot;third&quot;, &quot;fourth&quot;];

const values = prompts
  .map(p =&gt; parseInt(prompt(`${p} number: `),10))
  .filter(v =&gt; v !== 0);

const total = values.reduce((acc, val) =&gt; acc + val, 0);
const avg = total/values.length;

console.log(total, avg);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月14日 19:28:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75447180.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定