出于教育的原因,我正在研究一种简单的算法,该算法随机生成两个数字,然后要求将生成的数字相加,告诉您响应中是对还是错,并跟踪结果(不超过100个)。包含报告如下内容的函数:“您已经正确设置了80/100”但是我认为语法不适用。我无法获得分数变量来计算正确答案。
这是我的代码。
do{
var firstnum = Math.floor(Math.random()*10);
var secondnum = Math.floor(Math.random()*10);
var result = firstnum+secondnum;
var score=0;
var answer = prompt("what is "+firstnum + "+" + secondnum);
if(answer < result || answer > result){alert("Wrong! " + "The correct answer
is " + result)};
if(answer == result){alert("you are correct!"), score++};
alert("Awesome, You have gotten " + score + " correct so far!!!");}
while(score<100);
让我克服困难。我希望,如果我能通过这个小家伙,我真的可以把更多的概念弄清楚。
答案 0 :(得分:0)
您将每个循环中的score
重置为零。将声明和初始化移到顶部。
一些提示:
{ /* code */ }
之后不需要分号,+
将strinn转换为数字if
statement与else
块一起用于支票的对面。
// declare all variables at top
var firstnum,
secondnum,
result,
score = 0,
answer;
do {
firstnum = Math.floor(Math.random() * 10);
secondnum = Math.floor(Math.random() * 10);
result = firstnum + secondnum;
// covert input string to number with unary plus
answer = +prompt("what is " + firstnum + "+" + secondnum);
// ^
// just check the result and omit a second if clause,
// because it is just the opposite check
// take the more easy/shorter check first
if (answer === result ) {
alert("you are correct!");
score++;
} else {
alert("Wrong! " + "The correct answer is " + result)
}
alert("Awesome, You have gotten " + score + " correct so far!!!");
} while (score < 2) // take a small number for scoring check