cocos2d 随机数设计

来源:互联网 发布:雅思口语书 知乎 编辑:程序博客网 时间:2024/05/21 02:50

通常我们需要获得随机数的时候,假如直接使用了random()就会发现”为什么每次打开程序随机出来结果的顺序都一样?”,这是因为我们获得的随机数实际上都是伪随机数,所以在random之前需要使用srandom()函数获得一个seed来进行随机算法,并且通常是使用srandom(time(NULL)),把时间作为参数是为了获得的seed每次都不一样,当然理论上肯定是不一样的 XD

那么有没有更便捷的随机方法呢?

答案就是使用arc4random,它就藏在C语言标准库(Standard C Library)当中.文档对于它的描述是:

The arc4random() function uses the key stream generator employed by the arc4 cipher, which uses 8*8 8 bit S-Boxes. The S-Boxes can be in about (21700) states. The arc4random() function returns pseudo-random numbers in the range of 0 to (232)-1, and therefore has twice the range of rand(3) and random(3) .

arc4random既使用了arc4加密算法避免seed重复,并且比random的取值范围(2**31)-1整整大了一倍

在iPhone中,RAND_MAX是0x7fffffff (2147483647),而arc4random()返回的最大值则是 0×100000000 (4294967296),从而有更好的精度。此外,使用arc4random()还不需要生成随机种子,因为第一次调用的时候就会自动生成。
通过arc4random() 获取0到x-1之间的整数的代码如下:
int value = arc4random() % x;

获取1到x之间的整数的代码如下:

int value = (arc4random() % x) + 1;

其中,根据预算优先级括号实际是不需要的,不过我还是对括号格外小心。

最后如果想生成一个浮点数,可以在项目中定义如下宏:
#define ARC4RANDOM_MAX 0×100000000
然后就可以使用arc4random() 来获取0到100之间浮点数了(精度是rand()的两倍),代码如下:
double val = floorf(((double)arc4random() / ARC4RANDOM_MAX) * 100.0f);、


http://tenggangren.blog.163.com/blog/static/10585792020121141516591/