js基础——math工具

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        /*
          Math
            -Math和其他的对象不同,它不是一个构造函数
              它属于一个工具类,不用创建对象,它里边封装了数学运算相关的属性和方法
            -比如
               Math.PI 表示的圆周率
        */
        /*
          Math.abs()可以计算一个数的绝对值
          Math.ceil()向上取整
          Math.floor()向下取整
          Math.round()四舍五入取整
        */
        console.log(Math.PI);
        console.log(Math.abs(-5));
        console.log(Math.ceil(1.5));
        console.log(Math.floor(1.8));
        console.log(Math.round(3.2));

        //生成一个0~1之间的随机数
        console.log(Math.random());
        for(var i=0;i<=100;i++){
    
    
            //生成0~10的随机数
            //生成一个0~x之间的随机整数(万能公式)
            document.write(Math.round(Math.random()*10));
            //生成一个1~10之间的随机整数
            document.write(Math.round(Math.random()*9)+1);
            //生成一个x~y之间的随机数(万能公式,遇到此类题了套用)
            //document.write(Math.round(Math.random()*(y-x)+x));
            document.write("<hr>");
        }
        document.write("<hr>");
        document.write("<hr>");
        document.write("<hr>");
        /*
          max()可以获取多个数中的最大值
        */
        var max=Math.max(10,20,30);
        console.log(max);
        var min=Math.min(10,29,49,20);
        console.log(min);
        /*
          Math.pow(x,y)
          返回x的y次幂
        */

        console.log(Math.pow(4,2));
        //开方
        console.log(Math.sqrt(16));
    </script>
</head>
<body>
    
</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_44158539/article/details/113961973