我尝试使用javascript制作均值偏差计算器但是当我尝试输出|x-x̅|
的总和时,它总是返回0;
var frequencies = []
var output = document.getElementById("text")
function add() {
var score = document.getElementById("lol").value
frequencies.push(score)
}
function show() {
//Calculate the mean
var total = 0
var mean = 0
var scoreMinusMean = []
var summation = 0
for (i = 0; i < frequencies.length; i++) {
total += parseInt(frequencies[i])
}
mean = total / frequencies.length
//Gets the score - mean
for (j = 0; j < frequencies.length; j++) {
scoreMinusMean.push(Math.abs(frequencies[j] - mean))
}
for (k = 0; k < scoreMinusMean; k++) {
summation += scoreMinusMean[k]
}
output.innerHTML = scoreMinusMean
}
&#13;
<input id="lol">
<button onclick="add()">Add</button>
<button onclick="show()">Show</button>
Output: <span id="text"></span>
&#13;
答案 0 :(得分:1)
在您的上一个循环中,您所拥有的条件为k < scoreMinusMean
,您忘记在其中添加.length
。它应该是
for (k = 0; k < scoreMinusMean.length; k++) {
summation += scoreMinusMean[k]
}
此外,您应该在声明变量之前使用let
,否则它们将变为全局变量。
var frequencies = [];
var output = document.getElementById("text")
function add() {
var score = document.getElementById("lol").value
frequencies.push(score)
}
function show() {
//Calculate the mean
var total = 0
var mean = 0
var scoreMinusMean = []
var summation = 0
for (i = 0; i < frequencies.length; i++) {
total += parseInt(frequencies[i])
}
mean = total / frequencies.length
//Gets the score - mean
for (j = 0; j < frequencies.length; j++) {
scoreMinusMean.push(Math.abs(frequencies[j] - mean))
}
for (k = 0; k < scoreMinusMean.length; k++) {
summation += scoreMinusMean[k]
}
output.innerHTML = summation
}
&#13;
<input id="lol">
<button onclick="add()">Add</button>
<button onclick="show()">Show</button>
Output: <span id="text"></span>
&#13;
答案 1 :(得分:0)
您的代码的最后四行应该是:
for (k = 0; k < scoreMinusMean.length; k++) {
summation += scoreMinusMean[k]
}
output.innerHTML =summation/frequencies.length
}
当你忘记了阵列上的.length和标准偏差时,你需要再次平均偏差(即除以平均偏差的总和,除以元素的数量)。