zoukankan      html  css  js  c++  java
  • [前端技术]如何加深对JavaScipt中的Math.ceil() 、Math.floor() 、Math.round() 三个函数的理解

    首先还是看看《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)。

    代码
    1 <script type="text/javascript">
    2 /*
    3 ** 函数功能: 获取指定范围的随机数
    4 */
    5 function getRangeRandom(m, n, t)
    6 {
    7 var seed =0;
    8 switch(t)
    9 {
    10 // 随机数范围: m <= seed < n
    11  case0:
    12 seed = m + parseInt(Math.random() * n);
    13 break;
    14
    15 // 随机数范围: m <= seed < n
    16  case1:
    17 seed = m + Math.floor(Math.random() * n);
    18 break;
    19
    20 // 随机数范围: m < seed <= n
    21  case2:
    22 seed = m + Math.ceil(Math.random() * n);
    23 break;
    24
    25 // 随机数范围: m <= seed <= n
    26  case3:
    27 seed = m + Math.round(Math.random() * n);
    28 break;
    29 }
    30
    31 return seed;
    32 }
    33 </script>
  • 相关阅读:
    Pycharm中安装第三方库
    Cookie&Session区别
    在线AES加解密
    Python_base_正则表达式
    POST四种常见的传参区别
    SQL基础语法与规则
    SQL的4种连接
    Python_base_Log
    <11>Golang基础进阶——指针
    Shell脚本——特殊变量
  • 原文地址:https://www.cnblogs.com/JavCof/p/1724193.html
Copyright © 2011-2022 走看看