勵志

勵志人生知識庫

math的常用方法

Math的常用方法包括:

取絕對值:使用 `Math.abs()` 方法,例如 `Math.abs(-1)` 返回 `1`。

取整數:

`Math.ceil()` 方法用於向上取整,例如 `Math.ceil(1.2)` 返回 `2`,`Math.ceil(-1.1)` 返回 `-1`。

`Math.floor()` 方法用於向下取整,例如 `Math.floor(1.2)` 返回 `1`,`Math.floor(-1.2)` 返回 `-2`。

`Math.round()` 方法用於四捨五入,例如 `Math.round(1.5)` 返回 `2`,`Math.round(-1.5)` 返回 `-1`。

取最大/小值:

`Math.max()` 方法用於獲取最大值,例如 `Math.max(1, 2, 3)` 返回 `3`。

`Math.min()` 方法用於獲取最小值,例如 `Math.min(4, 5, 6)` 返回 `4`。

開方/冪:

`Math.sqrt()` 方法用於計算平方根,例如 `Math.sqrt(9)` 返回 `3`。

`Math.pow()` 方法用於計算冪,例如 `Math.pow(3, 2)` 返回 `9`。

常數:

`Math.PI` 常量表示圓周率,例如 `Math.PI` 返回 `3.141592653589793`。

獲取隨機數:

`Math.random()` 方法用於獲取0到1之間的隨機數(大於等於0且小於1)。

以上方法涵蓋了數學中常用的基本運算和函式,適用於各種編程場景。