我试图找到数组的中位数。我做了相当多的研究,如果这似乎被问过几次,没有令人满意的答案。
创建我的数组工作正常,但是当我调用该函数时,数组已排序但它返回不同的值,从 NaN 到数组的第一个值
如何找到长度的中值,然后从它的索引中找到数组的中值?
var ar1 = [];
while (true) {
var enterValues = prompt("enter your values");
if (enterValues != "") {
ar1.push(enterValues);
} else {
break;
}
}
function calcMedian() {
var half = Math.floor(ar1.length / 2);
ar1.sort(function(a, b) { return a - b;});
if (ar1.length % 2) {
return ar1[half];
} else {
return (ar1[half] + ar1[half] + 1) / 2.0;
}
}
console.log(ar1);
console.log(ar1.length);
console.log(calcMedian());
console.log(ar1);
(ps:要停止填充数组,只需输入无值即可。)
var ar1 = [];
while (true) {
var enterValues = prompt("enter your values");
if (enterValues != "") {
ar1.push(parseFloat(enterValues));
} else {
break;
}
}
function calcMedian() {
var half = Math.floor(ar1.length / 2);
ar1.sort(function(a, b) { return a - b;});
if (ar1.length % 2) {
return ar1[half];
} else {
return (ar1[half-1] + ar1[half]) / 2.0;
}
}
console.log(ar1);
console.log(ar1.length);
console.log(calcMedian());
console.log(ar1);
Math.floor(ar1.length)
将返回(例如)4
长度为8
. 但是,如果您这样做,ar1[4]
它实际上会返回数组中的第五项,因为数组索引从零开始。因此ar1[4-1]
将返回第四项,将其添加到ar1[4]
第五项并将其除以二以找到中位数。如果长度是奇数,它会返回(例如)3
如果长度是7
. 然后它检索arr[3]
作为中位数的第四项。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句