Cocoa生成随机数

来源:互联网 发布:小米平板刷windows 编辑:程序博客网 时间:2024/06/10 06:24
You should use the arc4random() function. It uses a superior algorithm to rand. You don't even need to set a seed.
arc4random, arc4random_stir, arc4random_addrandom -- arc4 random number generator

Same as C, you would do
int r = rand() % 74; // [0, 74)

Feel free to substitute random() or arc4random() for rand() (which is, as others have pointed out, quite sucky).

srandom((unsigned int)time(NULL)); // 防止出现警告



arc4random_uniform(74); // [0, 74)            

arc4random_uniform(upper_bound) avoids modulo bias as described in the man page:

arc4random_uniform() will return a uniformly distributed random number less than upper_bound. arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids "modulo bias" when the upper bound is not a power of two.

原创粉丝点击