问题描述
我尝试创建一个变量以使用 drand48() 随机获得值,但是在每次运行中,我的变量都采用相同的值.有人可以帮助我吗,(我希望每次运行时我的变量取不同的值)吗?
I try to create a variable to get value random with drand48 () but in each run my variable take a same value .can anybody help me , (i want in each run my variable take different value) ???
let number = drand48 ()
推荐答案
drand48创建一个伪随机数序列.也就是说,如果每次都没有将其设置为不同的起点,那么它将始终产生相同的数字.
drand48 creates a Pseudo-random number sequence. That is if it is not set to a different start point each time it will always produce the same numbers.
要提前解决此调用srand48,以设置drand48的新起点
To fix this call srand48 beforehand to set a new start point for drand48
例如
let time = UInt32(NSDate().timeIntervalSinceReferenceDate)
srand48(Int(time))
let number = drand48 ()
此处是drand48和srand48的文档
Here are the docs for drand48 and srand48
以不同的方式播种以避免发生错误,我不是在计算机上(在手机上),因此如果不起作用,可能稍后必须修复
different way to seed to avoid the error, I'm not by a computer (on my phone) so may have to fix it later if it doesn't work
这篇关于为什么drand48()在我的程序的每次运行中都显示相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!