【问题标题】:How to add 5 random numbers which are less than 10?如何添加 5 个小于 10 的随机数?
【发布时间】:2020-12-21 07:02:50
【问题描述】:

我创建了两个函数。一个创建 5 个随机数以将它们推入一个数组。另一个总结数字。随机数生成器正在工作并完美地制作一个数组。但总和并不准确。我找不到问题出在哪里。

//Generates 5 random numbers smaller than 10

function pushIntoArray() {
    let arr = [];
    let number;
    for(let i = 0; i < 5; i++) {
        number = Math.floor(Math.random() * 11);
        arr.push(number);
    }
    return arr;
}
console.log(pushIntoArray());

//Adds the numbers in arr
function sumNum(arr) {
    let total = 0;
    for(let i = 0; i < arr.length; i++) {
        total += arr[i];
    }
    return total;
}
let arr = pushIntoArray();
console.log(sumNum(arr));

【问题讨论】:

  • sumNum 函数将数组中的所有数字相加,并返回该总和的结果,因此在这方面它是准确的。你能解释一下为什么结果不准确吗?
  • 总和怎么不准确。当我调用pushIntoArray 时,我得到[ 1, 6, 10, 4, 9 ],然后正确地求和为30

标签: javascript arrays function math push


【解决方案1】:

因为您正在记录一组不同的数组值并检查不同组值的总和。 我已更改您的console.log 声明。

//Generates 5 random numbers smaller than 10

function pushIntoArray() {
    let arr = [];
    let number;
    for(let i = 0; i < 5; i++) {
        number = Math.floor(Math.random() * 11);
        arr.push(number);
    }
    return arr;
}

//Adds the numbers in arr
function sumNum(arr) {
    let total = 0;
    for(let i = 0; i < arr.length; i++) {
        total += arr[i];
    }
    return total;
}
let arr = pushIntoArray();
console.log(arr);
console.log(sumNum(arr));

【讨论】:

    【解决方案2】:

    您没有对您在控制台中登录的数组执行求和。您正在记录的是

    console.log(pushIntoArray()); // This is displayed in the console
    

    但是你正在通过调用生成一个 ney 数组

    let arr = pushIntoArray(); 
    

    但是您正在对 arr 数组执行求和,而不是在控制台中显示的数组。

    console.log(sumNum(arr)); // you did not console.log(arr) 
    

    函数正常工作,你只是在错误的地方调用它。

    【讨论】:

      【解决方案3】:

      该函数工作正常,但您正在记录不同的随机数数组并计算不同数组的总和。

      //Generates 5 random numbers smaller than 10
      
      function pushIntoArray() {
          let arr = [];
          let number;
          for(let i = 0; i < 5; i++) {
              number = Math.floor(Math.random() * 11);
              arr.push(number);
          }
          return arr;
      }
      // this array is different (this is not passed to the sumNum function)
      console.log(pushIntoArray());
      
      //Adds the numbers in arr
      function sumNum(arr) {
          let total = 0;
          for(let i = 0; i < arr.length; i++) {
              total += arr[i];
          }
          return total;
      }
      // this array is different
      let arr = pushIntoArray();
      console.log("sum of array:", arr)
      console.log(sumNum(arr));
      

      【讨论】:

        猜你喜欢
        • 2011-05-25
        • 1970-01-01
        • 2013-11-08
        • 1970-01-01
        • 1970-01-01
        • 2014-12-27
        • 2014-03-10
        • 2022-11-21
        • 2021-04-12
        相关资源
        最近更新 更多