我必须做一个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 );
发布于 2019-03-21 00:25:13
您可以通过执行以下操作在提示符和计数中包含文本:
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 );
当提示符出现时,文档不能写入。您还应该处理取消,以停止循环,而不是移动到下一个,并说您的猜测太低。
发布于 2019-03-21 00:36:22
你可能想要使用一个函数来实现这一点。
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();
https://stackoverflow.com/questions/55265504
复制相似问题