Calc中位数JavaScript

时间:2018-05-28 09:51:31

标签: javascript arrays median calc

我需要一个"中位数"按钮,用于计算表格中绘制数字的中位数。



<html>
<head>
<title> Numery losowania </title>
<script>
    var n1= Array.from({length: 9}, () => Math.floor(Math.random() * 70));
 
    document.writeln("<table border = \"1\"");

    n1.sort((a,b) => a-b); // sort the array
   
    for(var i=0; i < n1.length;i++)
    {
        document.writeln("<tr><td>" + n1[i] + "</td></tr>");
    }
    document.writeln("</table>");
</script>
<form>
<input type="button" value="Odśwież" onclick="location.reload()">
</form>
</head>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

您可以使用以下方法:

function median(numbers) {
    var median = 0, count = numbers.length;
    numbers.sort();

    if (count % 2 === 0) {  // is even
        median = (numbers[count / 2 - 1] + numbers[count / 2]) / 2;
    } else { // is odd
        median = numbers[(count - 1) / 2];
    }

    return median;
}

更新1: 根据您的要求

<script>
    function median(numbers) {
        var median = 0, count = numbers.length;
        numbers.sort();

        if (count % 2 === 0) {  // is even
            median = (numbers[count / 2 - 1] + numbers[count / 2]) / 2;
        } else { // is odd
            median = numbers[(count - 1) / 2];
        }

        document.getElementById("median").innerHTML = median;
    }

    var n1= Array.from({length: 9}, () => Math.floor(Math.random() * 70));
    ...
    ...
    document.writeln("</table>");
    document.writeln("<button onclick=median("+n1+")>Median</button>");
    document.writeln("<div id=\"median\"></div>");

</script>

答案 1 :(得分:0)

&#13;
&#13;
var n1= Array.from({length: 9}, () => Math.floor(Math.random() * 70));
n1.sort((a,b) => a-b); // sort the array

var tableData = "";
for(var i=0; i < n1.length;i++)
{
    tableData += "<tr><td>" + n1[i] + "</td></tr>";
}
document.getElementById("dataTable").innerHTML = tableData;

function getMedian() {
    if(n1.length%2==0)
      document.getElementById("medianDiv").innerHTML = "median is: "+(n1[(n1.length/2)-1]+n1[n1.length/2])/2;
    else
      document.getElementById("medianDiv").innerHTML =  "median is: "+n1[(n1.length-1)/2];
}
&#13;
<html>
<head>
<title> Numery losowania </title>
<form>
<input type="button" value="Odśwież" onclick="location.reload()">
<table border=1 id="dataTable"></table>
<input type="button" value="Get Median" onclick="getMedian()">
<div id="medianDiv"></div>
</form>
</head>
&#13;
&#13;
&#13;