mardi 13 juillet 2021

Finding the average of an array without hardcoding in JavaScript

I have to find the average score of:

scores = [85, 93, 65, 65, 92, 81, 93];

While I've been taught how to tackle this problem, I was told to do it without hardcoding which is somewhat of a problem to me because I'm a complete beginner. The hint was to use Math.random() which I already tried using.

let scores = [85, 93, 65, 65, 92, 81, 93];
let randDecimal = Math.random();
let randNum = randDecimal * scores.length;
let randIndex = Math.floor(randNum);
randScore = scores[randIndex];
let averageAddition = randScore * scores.length;
let averageLength = scores.length;
let averageScore = averageAddition / averageLength;
console.log("Average:", averageScore);

This prints different numbers which aren't average of scores I tried hard coding it and got a value of 82, now I can't seem to get 82 again.




Aucun commentaire:

Enregistrer un commentaire