javascript - 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 );
解决方案
您可以通过执行以下操作在提示中包含文本和计数:
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 );
提示出现时不会写入文档。您还应该处理取消以停止循环,而不是移动到下一个并说您的猜测太低。
推荐阅读
- javascript - 如何在 javascript 中解决此问题
- css - 在按钮焦点上,为什么我会得到两个不同的边框半径?
- typescript - 密钥名称具有已知前缀但完整密钥未知的打字稿接口
- google-sheets - 在 Google 表格中,如何合并包含部分重复条目的表格以仅返回最相关的信息?
- c# - .Net Core 3 AutoMapperMappingException:缺少类型映射配置或不支持的映射
- html - 如何使用自定义 css 类设置 WTForm 字段的样式?
- python - 错误:“无法执行脚本”使用命令 --noconsole
- javascript - 当角色仍然可用时,Discord 会显示 @deleted-role
- javascript - 使用光标捕获画布流
- azure-active-directory - 在已部署的 Microsoft Teams 自定义个人应用程序上使用 Microsoft Graph 工具包“本地主机拒绝连接”