I’ve created two functions. One to create 5 random numbers to push them into an array. And another one to sum up the numbers. The random number generator is working and making an array perfectly. But the sum is not accurate. I’m unable to find where the problem is.
//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));
Advertisement
Answer
Because you are logging a different set of array values and checking the sum of different set of array values.
I have changed your console.log
statement.
//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));