繁体   English   中英

Javascript练习

[英]Javascript exercise

我必须做一个javascript练习,我必须创建一个0到100之间的一个随机数,用户必须猜测,该程序将必须警告生成的数字是高还是低,并且必须计算尝试的次数。 我将下面的代码留给我使用,但是如果数目大于或小于该数目,则警告会在结尾时使我全部接受,而一次却一次,则我无法计数尝试次数。 有人可以帮我吗?

 var min=0; var max=10; var tent = 0; var random =Math.floor(Math.random() * (+max - +min)) + +min; document.write("Numero : " + random); document.write("<br>"); for (var i = 0;i < 10; i++){ var input = prompt("Indovina il numero" ); if (input < random){ document.write("Il valore è più grande <br>"); tent++; } else if (input > random) { document.write("Il valore è più piccolo <br>"); tent++; } else { document.write("Hai indovinato"); break; } } console.log( tent ); 

您可以通过以下方式在提示和计数中包括文本:

 var min=0; var max=10; var tent = 0; var text = ""; var random =Math.floor(Math.random() * (+max - +min)) + +min; document.write("Numero : " + random); document.write("<br>"); for (var i = 0;i < 10; i++){ var input = prompt("Indovina il numero. " + text + " Attempts: " + i); if (input < random){ text = "Il valore è più grande" document.write("Il valore è più grande <br>"); tent++; } else if (input > random) { text = "Il valore è più piccolo" document.write("Il valore è più piccolo <br>"); tent++; } else { document.write("Hai indovinato"); break; } } console.log( tent ); 

提示出现时,文档不会写。 您还应该处理取消以停止循环,而不要移至下一个循环并说您的猜测太低。

您可能要为此使用一个函数...

 var maxTries=10; var tries = 0; var min = 0 var max = 100; var random = Math.floor(Math.random() * (+max - +min)) + +min; function guess(){ tries++; if(tries>maxTries){ alert('You failed to guess the random number in '+maxTries+' tries!'); return; } var input = prompt("Guess the random number:" ); if(input>0){ if(input==random){ alert('Good job! You guessed the number in '+tries+' tries!'); }else if(input<random){ alert('Random number is larger than your guess...'); guess(); }else if(input>random){ alert('Random number is smaller than your guess...'); guess(); } } } guess(); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM