javascript中的Math.ceil() 、Math.floor() 、Math.round() 三个函数

本文详细介绍了JavaScript中的Math.ceil(), Math.floor() 和 Math.round() 函数,并通过实例展示了这些函数的应用,包括如何使用它们来生成指定范围内的随机数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先还是看看《The Definitive Guide, 4th Edition》书中对三个函数的的定义。

Math.ceil(x): round a number up

Arguments: Any numeric value or expression

Returns: The closest integer greater than or equal to x.

-----------------------------------------------------------------------------------------------------

Math.floor(x): round a number down

Arguments: Any numeric value or expression

Returns: The closest integer less than or equal to x.

-----------------------------------------------------------------------------------------------------

Math.round(x): round to the nearest integer

Arguments: Any number.

Returns: The integer closest to x.

 

通过对三个函数的原型定义的理解,其实很容易记住三个函数。

1. Math.ceil() 用作向上取整。

2. Math.floor() 用作向下取整。

3. Math.round() 用作四舍五入取整。

 

最后通过一个具体应用,进一步加深对三个函数的印象:

假设现在我要做一个Web Puzzle,需要获取一个指定范围的随机数,下面我会编写一个自定义函数getRangeRandom(m, n, t)。


<script type="text/javascript">
/*
    ** 函数功能: 获取指定范围的随机数
*/
function getRangeRandom(m, n, t)
    {
var seed =0;
switch(t)
        {
// 随机数范围: m <= seed < n
 case0:
                seed = m + parseInt(Math.random() * n);
break;
                
// 随机数范围: m <= seed < n
 case1:
                seed = m + Math.floor(Math.random() * n);
break;
            
// 随机数范围: m < seed <= n
 case2:
                seed = m + Math.ceil(Math.random() * n);
break;
            
// 随机数范围: m <= seed <= n
 case3:
                seed = m + Math.round(Math.random() * n);
break;
        }
        
return seed;
    }
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值