gpt4 book ai didi

JavaScript。如何将问题和正确答案返回到 Math.random

转载 作者:行者123 更新时间:2023-12-03 11:23:00 24 4
gpt4 key购买 nike

我对 javascript 相当陌生,并且遇到了问题。我找到了这个代码片段,并尝试在用户输入所有问题的答案后,显示问题、用户答案和 Ask() 的正确答案。我尝试使用 for 循环来显示每个索引,但这只是返回 true 或 false。

代码如下:

<script>
function ask() {
var a = Math.floor(Math.random() * 10) + 1;
var b = Math.floor(Math.random() * 10) + 1;
var op = ["*", "+", "/", "-"][Math.floor(Math.random()*4)];
return prompt("How much is " + a + " " + op + " " + b + "?") == eval( a + op + b);
}

var questions = [ask(), ask(), ask(), ask(), ask()],
total = questions.length,
correct = questions.filter(Boolean).length;


alert( "You got "+correct+"/"+total+" correctly");
</script>

并且可以测试当前代码here

最佳答案

参见http://jsfiddle.net/on1nnzpj/1/

ask() 返回一个函数,然后将给出的答案与正确答案进行比较:

function ask() {
var a = Math.floor(Math.random() * 10) + 1;
var b = Math.floor(Math.random() * 10) + 1;
var op = ["*", "+", "/", "-"][Math.floor(Math.random()*4)];
return new function() { this.op = op; this.ans = prompt("How much is " + a + " " + op + " " + b + "?"); this.cor = eval( a + op + b); this.suc = this.ans == this.cor};
}

function isCorrect(element){
return element.suc;
}

var questions = [ask(), ask(), ask(), ask(), ask()],
total = questions.length;
console.log(questions);
var correct = questions.filter(isCorrect).length;


alert( "You got "+correct+"/"+total+" correctly");
function alertQ(elem){
if (!elem.suc){
alert ("Your answer was: " + elem.ans + " correct answer was: " + elem.cor);
}
}
questions.forEach(alertQ);

更新

改变

return new function() { this.op = op; this.ans = prompt("How much is " + a + " " + op + " " + b + "?"); this.cor = eval( a + op + b); this.suc = this.ans == this.cor};

在此添加问题:

return new function() { this.op = op; this.q = "How much is " + a + " " + op + " " + b + "?"; this.ans = prompt(this.q); this.cor = eval( a + op + b); this.suc = this.ans == this.cor};

并修改alertQ:

您对问题 1:5 *4 的回答是 20。这是正确的!

function alertQ(elem, index){
var c = elem.cor ? " That was correct!" : " That was incorrect!"
alert ("Your answer for question " + (index + 1) + ": " + elem.q + " was: " + elem.ans + c);
}

关于JavaScript。如何将问题和正确答案返回到 Math.random,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27031289/

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