gpt4 book ai didi

javascript - 如何计算 JavaScript 测验的百分比分数?

转载 作者:行者123 更新时间:2023-11-30 14:10:45 25 4
gpt4 key购买 nike

我用 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 个问题。

最佳答案

您必须传递参数 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>")

关于javascript - 如何计算 JavaScript 测验的百分比分数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54506852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com