如何计算百分比得分在JavaScript测验?

问题描述 投票:1回答:2

我创建了一个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问题都答对了的例子。

javascript html
2个回答
2
投票

你必须传递参数得分,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>")

0
投票

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

问题的数量答对是score。问题总数为questions.length

所以,你的代码可以是这样的:

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

请注意,此代码需要来questionsscore已经声明,并且已经出现了进球。

© www.soinside.com 2019 - 2024. All rights reserved.