JavaScript 数学 (Math) 方法

2022/4/18 12:42:31

本文主要是介绍JavaScript 数学 (Math) 方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一、Math 方法

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

Math.round(7.8);    // 返回 8
Math.round(3.3);    // 返回 3

 

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

Math.random()    //返回随机整数

 

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

Math.pow(4, 2);      // 返回 16

 

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

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

 

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

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

 

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

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

 

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

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

 

8、Math.min() 和 Math.max() 可用于查找参数列表中的最低或最高值:

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

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

 

 

二、JavaScript 随机整数

Math.random() 与 Math.floor() 一起使用用于返回随机整数。

Math.floor(Math.random() * 10);		// 返回 0 至 9 之间的数

Math.floor(Math.random() * 11);		// 返回 0 至 10 之间的数

Math.floor(Math.random() * 10) + 1;	// 返回 1 至 10 之间的数

 



这篇关于JavaScript 数学 (Math) 方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程