如何在JavaScript中计算测验的百分比分数?

时间:2019-02-03 19:45:06

标签: javascript html

我已经用Javascript创建了一个测验,应该以HTML输出分数。提示用户测验问题,然后将其分数输出到HTML文件中。

我的问题可以很好地解决,但是我想将分数计算为百分比。

这是我的Javascript代码:

// Declare the "score" variable
var score = 0;
// Create the questions array
var questions = [
["T or F: Two plus two is ten."],
["T or F: George Washington was the first U.S.president."],
["T or F: Al Gore is our current Vice President."],
["T or F: Two plus two is four."],
["T or F: You are not an alien from Mars."]
];
// Create the answer key array
var answer_key = [
["F"],
["T"],
["F"],
["T"],
["T"]
];
// Ask each question
function askQuestion(question) {
  var answer = prompt(question[0], "");
  if (answer.toUpperCase() == answer_key[i]) {
    alert("Correct!");
    score++;
  } else if (answer==null || answer=="") {
    alert("You must enter T or F!");
    i--;
  } else {
    alert("Sorry. The correct answer is " + answer_key[i]);
  }
}
for (var i = 0; i < questions.length; i++) {
  askQuestion(questions[i]);
}

// Caclulate score
function scoreTest(answer, questions) {
var score = (answer/questions) * 100;
return score;
}

以下是应在其中显示输出的HTML代码:

<script>
var message = "Your score for the test is " + scoreTest(answer, questions);
document.write("<p>" + message + "</p>")
</script>

如果输出/功能正常工作,则应显示“您的测试分数为80%”,例如,假设正确回答了4/5个问题。

2 个答案:

答案 0 :(得分:2)

您必须传递参数score和questions.length来计算百分比,因为您仅在scoretest函数中传递了变量名。 您的代码

scoreTest(answer, questions);

应该是什么

scoreTest(score, questions.length);

// Declare the "score" variable
var score = 0;
// Create the questions array
var questions = [
["T or F: Two plus two is ten."],
["T or F: George Washington was the first U.S.president."],
["T or F: Al Gore is our current Vice President."],
["T or F: Two plus two is four."],
["T or F: You are not an alien from Mars."]
];
// Create the answer key array
var answer_key = [
["F"],
["T"],
["F"],
["T"],
["T"]
];
// Ask each question
function askQuestion(question) {
  var answer = prompt(question[0], "");
  if (answer.toUpperCase() == answer_key[i]) {
    alert("Correct!");
    score++;
  } else if (answer==null || answer=="") {
    alert("You must enter T or F!");
    i--;
  } else {
    alert("Sorry. The correct answer is " + answer_key[i]);
  }
}
for (var i = 0; i < questions.length; i++) {
  askQuestion(questions[i]);
}

// Caclulate score
function scoreTest(answer, questions) {
var score = (answer/questions) * 100;
return score;
}
var message = "Your score for the test is " + scoreTest(score, questions.length);
document.write("<p>" + message + "%</p>")

答案 1 :(得分:0)

计算分数的分子应为正确回答的问题数。分母应该是问题的总数。

正确回答的问题数为score。 问题总数为questions.length

因此您的代码如下所示:

let message = `Your score for the test is ${(score / questions.length) * 100}%`;
document.write(`<p>${message}</p>`);

请注意,此代码需要在声明questionsscore之后并进行计分之后出现。