Math

一 概念

#### 1、常用常量

```js
E:返回算术常量 e,即自然对数的底数(约等于2.718)
LN2:返回 2 的自然对数(约等于0.693)
LN10:返回 10 的自然对数(约等于2.302)
LOG2E:返回以 2 为底的 e 的对数(约等于 1.4426950408889634)
LOG10E:返回以 10 为底的 e 的对数(约等于0.434)
PI:返回圆周率(约等于3.14159)
```

#### 2、常用方法

```js
abs(x):返回 x 的绝对值
ceil(x):向上取整
floor(x):向下取整
max(...n):求最大值
min(...n):求最小值
pow(x,y):返回 x 的 y 次幂
random():返回 0 ~ 1 之间的随机数
round(x):四舍五入
```

二 代码示范

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Math</title>
</head>
<body>
Math
</body>
<script type="text/javascript">
// 常量
console.log(Math.PI);
// 常用方法
console.log(Math.abs(-10)); // 绝对值
console.log(Math.floor(3.9)); // 向下取整
console.log(Math.max(3, 5, 7, 1, 9.5)) // 取大值

// 随机数: [0, 1)
console.log(Math.random());
// [0, 5)
// Math.random() * 5;

// [0, 5]整数
// Math.floor(Math.random() * 6); // [0, 6) => 向下取整 => [0, 5]
// parseInt(Math.random() * 6); // [0, 6) => 取整数部分 => [0, 5]

console.log("------------------------------------------");
// for (var i = 0; i < 20; i++) {
// console.log(parseInt(Math.random() * 6));
// }

// [5, 10]
// [0, 5]整数 + 5
// parseInt(Math.random() * 6) + 5


// [min, max]
// parseInt(Math.random() * (max - min + 1)) + min

function randomNum(min, max) {
return parseInt(Math.random() * (max - min + 1)) + min;
}
for (var i = 0; i < 20; i++) {
console.log(randomNum(5, 8));
}
</script>
</html>

posted @ 2018-10-17 17:50  不沉之月  阅读(140)  评论(0编辑  收藏  举报