4.3 數學(Math)
在 javascript/practice
資料夾下,建立 math.html
來練習。
JavaScript 提供了一個 Math
物件,讓我們可以針對數學的領域中,進行一些基本的操作,如下:
Math.PI
console.log(Math.PI); // 3.141592653589793
Math.abs()
將數值轉成正數,例:
console.log(Math.abs(-4.7)); // 4.7
Math.round()
四捨五入的近似值,例:
console.log(Math.round(4.5)); // 5
console.log(Math.round(4.4)); // 4
console.log(Math.round(-4.5)); // -4 (留意:不是 -5)
console.log(Math.round(-4.4)); // -4
console.log(Math.round(-4.5001)); // -5
console.log(Math.round(-4.4999)); // -4
Math.pow()
指數,某數的幾次方:
Math.pow(8, 2); // 64
Math.pow(2, 3); // 8
Math.sqrt()
開根號:
Math.sqrt(64); // 8
Math.ceil()
無條件進位到較大整數:
console.log(Math.ceil(4.4)); // 5
console.log(Math.ceil(-4.4)); // -4
Math.floor()
無條件進位到較小整數:
console.log(Math.floor(4.4)); // 4
console.log(Math.floor(-4.4)); // -5
Math.min()
在所有的數值參數當中,找出最小值:
console.log(Math.min(0, 150, 30, 20, -8, -200)); // -200
Math.max()
在所有的數值參數當中,找出最大值:
console.log(Math.max(0, 150, 30, 20, -8, -200)); // 150
Math.random()
在數值 0 ~ 1 之間,隨機產生小數點。(有包含 0,但不包含 1)。
以下程式同學執行看看:
console.log(Math.random());
練習
在 console 中,隨機印出 0 ~ 9 的整數。
在 console 中,隨機印出 0 ~ 10 的整數。
在 console 中,隨機印出 1 ~ 10 的整數。
在 console 中,隨機印出 1 ~ 100 的整數。
參考作法:
Last updated