html生成随机数(小数或整数)并以按钮形式输出

代码

按钮形式

<script>
function Num()
{
     
     
	document.getElementById("field").value=Math.floor(Math.random()*5+5) + Math.ceil(Math.random()*10)/10
}
</script>
<button onclick="Num()">输出5-10的随机数</button> <input type="text" id="field">

文本形式

<script language="javascript">
var a=parseInt(Math.random()*100);
document.write("输出随机数:",a);
</script>

效果

按钮形式(可多次按下) 文本形式

语法

Math.ceil() 向上取整。
Math.floor() 向下取整。
Math.round() 四舍五入。
Math.random() [0.0 ~ 1.0) 区间一个伪随机数
通过组合上面的简单语法可以生成更复杂的语法:
Math.ceil(Math.random()*10) 获取从1到10的随机整数 ,取0的概率极小。
Math.round(Math.random()) 可均衡获取0到1的随机整数。
Math.floor(Math.random()*10) 可均衡获取0到9的随机整数。
Math.round(Math.random()*10) 获取0到10的随机整数,其中获取最小值0和最大值10的几率少一半。

因此上文的Math.floor(Math.random()*5+5) + Math.ceil(Math.random()*10)/10可以生成5-10的一位随机数;

参考

  1. html事件属性
  2. html<button>标签
  3. js生成[n,m]的随机数

猜你喜欢

转载自blog.csdn.net/qq_34769162/article/details/108670172