向比我更有知识的人寻求一些指导。
我正在编写一个程序,提示用户单击一个按钮,然后生成一个 1 到 100 之间的随机整数。
我可以很好地处理这部分。我正在努力解决的是让程序打印这个随机整数的范围,即 i<=33。
例如,当我单击我想看到的按钮时:
“10是小于33的数字”
或
“55 是 33 到 66 之间的数字”
这是到目前为止我的代码,我已将遇到问题的代码放在注释中。
<!DOCTYPE HTML5>
<html>
<head>
<meta charset="UTF-8">
<title>question2</title>
</head>
<body>
<p>Click the button to display a random number from 1 to 100.</p>
<button onclick="myFunction()">Click here</button>
<p id="demo"></p>
<script>
function myFunction() {
var text = "";
var i = Math.floor((Math.random() * 100) + 1);
document.getElementById("demo").innerHTML = i;
}
// if (myFunction <= 33) {
// text += ("<br>" + i + " is a number less than or equal to 33");
// }
// if (myFunction > 34 and i < 65) {
// text += ("<br>" + i + " is a number between 33 and 66 (exclusive)");
// }
// if (my Function >= 66) {
// text += ("<br>" + i + " is a number greater than or equal to 66");
// }
</script>
</body>
</html>
谢谢大家。
最佳答案
您可以测试,如果true
显示结果并退出。
function getRandom() {
var i = Math.floor((Math.random() * 100) + 1);
if (i <= 33) {
document.getElementById("demo").innerHTML += i + " is a number less than or equal to 33<br>";
return;
}
if (i < 66) {
document.getElementById("demo").innerHTML += i + " is a number between 33 and 66 (exclusive)<br>";
return;
}
document.getElementById("demo").innerHTML += i + " is a number greater than or equal to 66<br>";
}
<p>Click the button to display a random number from 1 to 100.</p>
<button onclick="getRandom()">Click here</button>
<p id="demo"></p>
关于javascript - 随机数生成器 Javascript - 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41351368/