JS随机生成20个数 范围20~50 计算和的平均数的代码怎样写?
/* 获取[20,50]范围内随机整数20个,并求这些随机数的平均值*/
function randomF() {
var aNumber = (50 + 1 - 20) * Math.random() + 20;
var result = Math.floor(aNumber);
return result;
}
var arr = [];
var counter = 0,
sum = 0,
result = null;
var timer = setInterval(function () {
counter++;
if (counter == 21) {
clearInterval(timer);
} else {
arr.push(randomF());
}
}, 10);
setTimeout(function () {
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
result = sum / arr.length;
console.log(arr)
console.log(result)
}, 201)