首页 > 解决方案 > Javascript 练习

问题描述

我必须做一个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 );

标签: javascripthtml

解决方案


您可以通过执行以下操作在提示中包含文本和计数:

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 );

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


推荐阅读