首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript练习

Javascript练习
EN

Stack Overflow用户
提问于 2019-03-21 00:16:56
回答 2查看 108关注 0票数 1

我必须做一个javascript练习,我必须创建一个介于0和100之间的随机数,用户必须猜测,如果生成的数字更高或更低,程序将不得不发出警告,并且必须计数所做的尝试。我在下面留下了对我有效的代码,但是如果数字大于或小于这个数字,警告会在最后给我所有的尝试,而不是一次一个,我不能计算尝试的次数。有人能帮帮我吗?

代码语言:javascript
复制
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 );

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-03-21 00:25:13

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

代码语言:javascript
复制
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 );

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

票数 1
EN

Stack Overflow用户

发布于 2019-03-21 00:36:22

你可能想要使用一个函数来实现这一点。

代码语言:javascript
复制
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();

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55265504

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档