Javascript初学者在这里。我正在尝试使用窗口提示计算一个简单的数学函数(什么是3 + 3 =?)。如果用户得到正确答案,我希望它报告回来(正确!),但如果他们离正确答案(5或7)一个,我希望它报告另一个窗口提示说(非常接近请再试一次)什么是3 + 3?)但是,如果他们得到完全错误的答案(让我们说他们放入2)我希望它报告回来(不正确请再试一次。什么是3 + 3 =?)这第三个条件是什么给了我问题,因为我在脚本中需要2个单独的循环,我不知道该怎么做。
到目前为止,这是我的代码,我遇到的是第三次循环
var answer = window.prompt("What is 3+3", "");
answer=parseFloat(answer);
if(answer==6){
document.write("Correct!");
}else while( answer==5 || answer==7){
answer=window.prompt("Very Close Please Try again. What is 3+3", "");
}else while(answer!==6 && answer!==5 && answer!=7){
answer=window.prompt("Incorrect. Please try again. What is 3+3", "");
}
也可以向任何人解释如何使用随机数并回答这个数字而不是硬编码的3 + 3及其答案。
答案 0 :(得分:3)
试试这个
var answer = parseInt( window.prompt("What is 3+3", "") );
while( answer !== 6 )
{
if ( answer === 5 || answer === 7 )
{
answer = parseInt( window.prompt( "Very Close Please Try again. What is 3+3", "") );
}
else if( answer !== 6 )
{
answer = parseInt( window.prompt("Incorrect. Please try again. What is 3+3", "") );
}
}
document.body.innerHTML = "Correct!";
答案 1 :(得分:1)
这种方式将是动态的。 。
<body></body>
<script type="text/javascript">
var firstval = 5;
var secondval = 3;
var sum = firstval + secondval;
var answer = parseInt( window.prompt("What is "+firstval+" + "+secondval, ""));
while( answer !== sum )
{
if ( answer === sum - 1 || answer === sum + 1 )
{
answer = parseInt( window.prompt( "Very Close Please Try again. What is "+firstval+" + "+secondval+"", "") );
}
else if( answer !== sum )
{
answer = parseInt( window.prompt("Incorrect. Please try again. What is "+firstval+" + "+secondval+"", "") );
}
}
document.body.innerHTML = "Correct!";
</script>