Js-w3school(2020.2.5)【js数学】

十四、js数学

1.Math.round(x) 的返回值是 x 四舍五入为最接近的整数:

Math.round(6.8);    // 返回 7
Math.round(2.3);    // 返回 2

2.Math.pow(x, y) 的返回值是 x 的 y 次幂:

Math.pow(8, 2); // 返回 64

3.Math.sqrt(x) 返回 x 的平方根:

Math.sqrt(64);      // 返回 8

4.Math.abs(x) 返回 x 的绝对(正)值:

Math.abs(-4.7);     // 返回 4.7

5 Math.ceil(x) 的返回值是 x 上舍入最接近的整数:

Math.ceil(6.4);     // 返回 7

6 Math.floor(x) 的返回值是 x 下舍入最接近的整数:

Math.floor(2.7);    // 返回 2

7 Math.sin(x) 返回角 x(以弧度计)的正弦(介于 -1 与 1 之间的值)。
如果您希望使用角度替代弧度,则需要将角度转换为弧度制:
Angle in radians = Angle in degrees x PI / 180.
比如

Math.sin(90 * Math.PI / 180);     // 返回 1(90 度的正弦)

8.Math.cos(x) 返回角 x(以弧度计)的余弦(介于 -1 与 1 之间的值)。
9. Math.min() 和 Math.max() 可用于查找参数列表中的最低或最高值:

Math.min(0, 450, 35, 10, -8, -300, -78);  // 返回 -300
Math.max(0, 450, 35, 10, -8, -300, -78);  // 返回 450

10 Math.random() 返回介于 0(包括) 与 1(不包括) 之间的随机数:

Math.random();     // 返回[0,1)随机数

11.Math常量

Math.E          // 返回欧拉指数(Euler's number)
Math.PI         // 返回圆周率(PI)
Math.SQRT2      // 返回 2 的平方根
Math.SQRT1_2    // 返回 1/2 的平方根
Math.LN2        // 返回 2 的自然对数
Math.LN10       // 返回 10 的自然对数
Math.LOG2E      // 返回以 2 为底的 e 的对数(约等于 1.414)
Math.LOG10E     // 返回以 10 为底的 e 的对数(约等于0.434)

在这里插入图片描述
在这里插入图片描述
13.随机数
(1)随机整数

Math.random() 与 Math.floor() 一起使用用于返回随机整数。
Math.floor(Math.random() * 10);		// 返回 0 至 9 之间的数
Math.floor(Math.random() * 100) + 1;	// 返回 1 至 100 之间的数

(2)适当随机数
这个 JavaScript 函数始终返回[min, max)之间的随机数:

function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min) ) + min;
}

这个 JavaScript 函数始终返回介于[min, max]之间的随机数:

function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min + 1) ) + min;
}
发布了41 篇原创文章 · 获赞 4 · 访问量 1647

猜你喜欢

转载自blog.csdn.net/mus123/article/details/104186790