如何添加5个小于10的随机数


我创建了两个函数。一个是创建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));

因为您正在记录一组不同的数组值,并检查不同数组值的总和。我更改了您的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));

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

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

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

let arr = pushIntoArray(); 

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

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

该函数工作正常,您只是在错误的事情上调用它。

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

//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));

最新更新