codecamp

CoffeeScript 生成随机数

生成随机数

问题

你需要生成在一定范围内的随机数。

解决方案

使用JavaScript的Math.random()来获得浮点数,满足0<=X<1.0。使用乘法和Math.floor得到在一定范围内的数字。

probability = Math.random()
0.0 <= probability < 1.0
# => true

# 注意百分位数不会达到 100。从 0 到 100 的范围实际上是 101 的跨度。
percentile = Math.floor(Math.random() * 100)
0 <= percentile < 100
# => true

dice = Math.floor(Math.random() * 6) + 1
1 <= dice <= 6
# => true

max = 42
min = -13
range = Math.random() * (max - min) + min
-13 <= range < 42
# => true

讨论

对于JavaScript来说,它更直接更快。

需要注意到JavaScript的Math.random()不能通过发生器生成随机数种子来得到特定值。详情可参考产生可预测的随机数

产生一个从0到n(不包括在内)的数,乘以n。
产生一个从1到n(包含在内)的数,乘以n然后加上1。

CoffeeScript 生成可预测的随机数
CoffeeScript 转换弧度和度
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

CoffeeScript 数据库

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }