JavaScript 学习笔记——Math属性及其方法

本文详细介绍了JavaScript中如何使用Math.random()生成不同范围内的随机数,并结合Math.floor(), Math.ceil()及Math.round()函数实现随机整数的生成。通过实例展示了生成指定区间内随机数的具体方法。

Math.random() — 返回0和1之间的伪随机数 可能为0,但总是小于1,[0,1)。

Math.random()*10//返回 0-10 之间的随机数。
Math.random()*(20-10)+10 //返回10-20之间的随机数。
Math.random()*(n-m)+m //返回(m-n)之间的随机数。 

Math.floor() -- 向下取得一个最接近的整数

Math.floor(12.2)// 返回12 
Math.floor(12.7)//返回12 
Math.floor(12.0)//返回1

Math.ceil() -- 向上取得一个最接近的整数

Math.ceil(12.2)//返回13 
Math.ceil(12.7)//返回13 
Math.ceil(12.0)// 返回12

Math.round() -- 进行四舍五入

Math.round(12.2)// 返回12 
Math.round(12.7)//返回13 
Math.round(12.0)//返回12

这些函数平常实际使用中大多相互配合:例如要想生成 0 - 10 之间的随机整数,可以这样写

Math.floor(Math.random()*10);
//其中Math.random()*10返回 [0 - 10)之间的随机数,再利用Math.floor(),只取出其中的整数。

Math.ceil(Math.random()*10);
//那么依据上述介绍,这样因为Math.ceil()向上取整,那么则返回 [1 - 10] 之间的随机整数。

转载于:https://www.cnblogs.com/eaysun/p/4385801.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值