代码没有给出正确和错误答案的不同分数,我需要它来给出问题的总分;即使你提出了错误的答案,它也说你还有3/3
<html>
<head>
<title>
00000
</title>
</head>
<body>
<script>
//variables
var q1 = parseInt(prompt("What data type is a number? " + " A:Boolean
B: Integer C: String"));
var q2 = parseInt(prompt(" What operator means not equal to? " + " A:<
B: = = C: !="));
var q3 = parseInt(prompt(" Which function is used to square root?" + "A:
math.sqrt B: math.pi C: math.pow"));
var score1 = 0;
var score2 = 0;
var score3 = 0;
//calculate score
if (q1 = "B")
score1 = 1
else if (q1 = "A" || "C")
score1 = 0
if (q2 = "C")
score2 = 1
else if (q1 = "A" || "B")
score2 = 0
if (q3 = "A")
score3 = 1
else if (q1 = "B" || "C")
score3 = 0
totalScore = score1 + score2 + score3;
//output
alert("Total score = " + totalScore + "/3");
</script>
</body>
</html>
答案 0 :(得分:2)
你正在使用赋值算子而不是在你的描述中进行比较。
if (q1 === "B")
score1 = 1
else
score1 = 0
如果在使用=时可以将“B”分配给q1,则第一个eval将始终返回true 使用==或===来评估q1是否与“B”相同。
答案 1 :(得分:1)
我认为您可以使用ternary大大简化代码。像,
var q1 = "A";
var q2 = "B";
var q3 = "C";
var score1 = (q1 === "B") ? 1 : 0;
var score2 = (q2 === "C") ? 1 : 0;
var score3 = (q3 === "A") ? 1 : 0;
var totalScore = score1 + score2 + score3;
alert("Total score = " + totalScore + "/3");
&#13;
答案 2 :(得分:0)
首先,如果您希望prompt
上有字符串响应,则不应该在响应中运行parseInt()
,因为您随时可以获得NaN
输入非整数因此使您的进一步测试失效。
其次,如前所述,要进行比较,您应该使用==
或===
代替=
。
最后,有很多方法可以大大简化此脚本,例如以下:
// Store the responses and answers in their own arrays
var responses = [
prompt("What data type is a number? " + " A: Boolean B: Integer C: String "),
prompt(" What operator means not equal to? " + " A: < B: == C: != "),
prompt(" Which function is used to square root?" + "A: math.sqrt B: math.pi C: math.pow ")
],
answers = ['B','C','A'], // Store the correct answers in order
score = 0; // Start off the score at zero.
// Match each response with it's respective answer
// and add +1 to the score if they match...
// Also, make sure the input is a string so toUpperCase() works (in case someone answers in lowercase)
for(x in responses) {
score = (typeof responses[x] == 'string' && responses[x].toUpperCase() == answers[x]) ? score+1 : score;
}
// Show score
alert('You scored ' + score + '/3');