2016-07-11 34 views
1

如何使用php對此測試進行評分?我需要一個百分比...在php中使用加權平均數進行評分

我有一系列的問題,包含正確/不正確的布爾和相應的重量。

我需要先找到正確答案的平均值嗎?

方程是什麼?

$questions = array(
    0=>array(
     'Question'=>"Some Question", 
     'Correct'=>true, 
     'Weight'=>5, 
    ), 
    1=>array(
     'Question'=>"Some Question", 
     'Correct'=>false, 
     'Weight'=>5, 
    ), 
    2=>array(
     'Question'=>"Some Question", 
     'Correct'=>true, 
     'Weight'=>4, 
    ), 
    3=>array(
     'Question'=>"Some Question", 
     'Correct'=>true, 
     'Weight'=>0, 
    ), 
    4=>array(
     'Question'=>"Some Question", 
     'Correct'=>false, 
     'Weight'=>5, 
    ), 
    5=>array(
     'Question'=>"Some Question", 
     'Correct'=>true, 
     'Weight'=>4, 
    ), 
); 
$weights = array(
    0=>0 
    1=>0 
    2=>.05 
    3=>.20 
    4=>.25 
    5=>.50 
); 
$totalQuestions=0; 
$correctAnswers=0; 
$points=0; 
foreach($questions as $question){ 
    $totalQuestions++; 
    if($question['Correct']){ 
     $correctAnswers++; 
     $points = $points = $weights[$question['Weight']; 
    } 
} 

回答

0

可以計算權重的候選人贏得的金額(即你有個點),然後將總的權重可能(即滿分)。

然後你就可以將通過總分考生的分數:

得分=候選得分/總比分

從那裏,你可以計算出百分比:

百分比=分數* 100

使用代碼:

$totalQuestions=0; 
$totalWeights=0; 
$correctAnswers=0; 
$weightsEarned=0; 
foreach($questions as $question){ 
    $totalQuestions++; 
    $totalWeights+=$weights[$question['Weight']]; 
    if($question['Correct']){ 
     $correctAnswers++; 
     $weightsEarned += $weights[$question['Weight']]; 
    } 
} 

echo "Score Overview: "; 
echo "<br/>Weights Earned: " . $weightsEarned; 
echo "<br/>Correct Answers: " . $correctAnswers; 
echo "<br/>Total Weights Possible : " . $totalWeights; 
echo "<br/>Percentage Earned: " . ($weightsEarned/$totalWeights) * 100; 
0

通常的平均(加權或不)是事物超過總的可能的事情的總和。如果它的加權通常意味着每件事情不是1件事情,但實際上是weightOfThing事情。

例子:

$totalQuestions = count($questions); //No need to increment 
$totalWeight = 0; //Could do a sum here but no need 
$weightedSum = 0; 
foreach($questions as $question){ 
    $totalWeight += isset($question["Weight"])?$question["Weight"]:0; //Assume a question with no weight has 0 weight, i.e., doesn't count. Adjust accordingly 
    if($question['Correct']){ 
     $weightedSum += isset($question["Weight"])?$question["Weight"]:0; 
    } 
} 
$weightedAverage = $weightedSum/$totalWeight; 
0

可以優化,但這裏是已完成的公式:

$weights = array(
    0=>0, 
    1=>0, 
    2=>.05, 
    3=>.20, 
    4=>.25, 
    5=>.50, 
); 

$byWeight = array(); 
foreach($questions as $question){ 
    //$totalQuestions++; 
    $byWeight[$question['Weight']]['TotalNumberOfQuestionsForWeight']++; 
    if($question['Correct']){ 
     $byWeight[$question['Weight']]['CorrectAnswers']++; 
    } 
} 

$totalWeightsSum = 0; 
foreach($byWeight as $weight => $data){ 
    $totalWeightsSum = $totalWeightsSum + (($data['CorrectAnswers']/$data['TotalNumberOfQuestionsForWeight']) * $weights[$weight]); 
} 

echo '<pre>'.var_export($byWeight,1).'</pre>'; 
echo $totalWeightsSum/array_sum($weights);