用 Math.random 隨機產生整數時,為什麼通常是用 Math.floor 而不是 Math.ceil
Math.random() 的範圍:0 ≤ Math.random() < 1 如果要隨機產生 0~9 這十個數字 使用 Math.floor: 0 ≤ Math.random() * 10 < 10 0 ≤ Math.floor(Math.random()) * 10 ≤ 9 使用 Math.ceil: 0 ≤ Math.random() * 9 < 9 0 ≤ Math.ceil(Math.random()) * 9 ≤ 9 但是 Math.random() 產生 0 的機率非常非常非常非常小,所以 「Math.ceil(Math.random()) * 9」骰出 0 的機率非常非常非常非常小。 相關討論: Random Number, Math.floor(…) vs Math.ceil(…) - stack overflow