Fork me on GitHub

ios中的随机数使用

有如下三种随机数方法:
1.    srand((unsigned)time(0));
        int i = rand() % 5;      

2.    srandom(time(0));
        int i = random() % 5;

3.    int i = arc4random() % 5 (常用) ;

 

注:rand()实际并不是一个真正的伪随机数发生器,random()会相对好点,但也不算理想。个人来说首选arc4random() ,原因就是它是一个真正的伪随机算法,而且范围是rand()的两倍。


在iPhone中,RAND_MAX是0x7fffffff (2147483647),而arc4random()返回的最大值则是 0x100000000 (4294967296),从而有更好的精度。此外,使用arc4random()还不需要生成随机种子,因为第一次调用的时候就会自动生成。

 

注:    //NSLog(@"%f",(CGFloat)arc4random()/((0>>1)-1));打印出来是负数,因为最高位符号位是1

        //NSLog(@"%f",((CGFloat)arc4random()/((1<<31)-1))/2);来代替    输出(0~1)范围的浮点数

参考:

http://www.cocoachina.com/bbs/read.php?tid=70719&keyword=%CB%E6%BB%FA%CA%FD

http://www.cocoachina.com/bbs/read.php?tid-2977-fpage-2-toread--page-1.html

http://www.codeios.com/thread-310-1-1.html

posted on 2012-02-14 12:29  pengyingh  阅读(543)  评论(0编辑  收藏  举报

导航