我有一个问答应用程序,询问3个问题。随着时间的推移,我会跟踪正确/错误的答案,如下所示:
var c0 = 143; // Number of users who got 0 questions correct
var c1 = 278; // Number of users who got 1 question correct
var c2 = 236; // Number of users who got 2 questions correct
var c3 = 185; // Number of users who got 3 questions correct
如何计算用户答对的平均值个问题?
var averageCorrectQuestions = 2.15; // Example (out of 3)
答案 0 :(得分:1)
您可以将计数与正确问题的计数相乘,求和该值,然后对所有用户计数。结果将总数除以计数。
var c0 = 143,
c1 = 278,
c2 = 236,
c3 = 185,
[sum, count] = [c0, c1, c2, c3].reduce(([s, c], n, v) => [s + n * v, c + n], [0, 0]);
console.log(sum, count);
console.log(sum/count);
答案 1 :(得分:0)
您可以编写一个用于计算和的函数,并编写一个用于获取平均值的函数:
function sum(arr) {
return arr.reduce((s, next) => s + next, 0)
}
function average(arr) {
return (arr.length ? sum(arr) / arr.length : 0)
}