如何在变量中存储迭代的结果



出于教育的原因,我正在使用一种简单的算法,随机生成两个数字,然后要求添加生成的数字,告诉你的回答是对还是错,并跟踪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); 

帮我渡过难关。如果我能理解这个小家伙,我希望我能真正理解更多的概念。

您将每个循环中的score重置为零。将声明和初始化移到顶部。

一些提示:

  • 在块语句CCD_ 2之后不需要分号
  • 用一元加+将字符串转换为数字
  • 使用带有else块的单个if语句作为检查的对立面

// 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

最新更新