我主要是一个Java高手,我想要一种生成0到74之间的伪随机数的方法.在Java中,我会使用以下方法:

Random.nextInt(74)

我对关于种子或真正随机性的讨论不感兴趣,只对你如何在Objective-C中完成同样的任务感兴趣.我搜索了谷歌,似乎有很多不同且相互冲突的信息.

推荐答案

你应该使用arc4random_uniform()函数.它使用了比rand更好的算法.你甚至不需要 seeder .

#include <stdlib.h>
// ...
// ...
int r = arc4random_uniform(74);

arc4random人页面:

NAME
     arc4random, arc4random_stir, arc4random_addrandom -- arc4 random number generator

LIBRARY
     Standard C Library (libc, -lc)

SYNOPSIS
     #include <stdlib.h>

     u_int32_t
     arc4random(void);

     void
     arc4random_stir(void);

     void
     arc4random_addrandom(unsigned char *dat, int datlen);

DESCRIPTION
     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 (2**1700) states.  The arc4random() function returns pseudo-
     random numbers in the range of 0 to (2**32)-1, and therefore has twice the range of rand(3) and
     random(3).

     The arc4random_stir() function reads data from /dev/urandom and uses it to permute the S-Boxes via
     arc4random_addrandom().

     There is no need to call arc4random_stir() before using arc4random(), since arc4random() automatically
     initializes itself.

EXAMPLES
     The following produces a drop-in replacement for the traditional rand() and random() functions using
     arc4random():

           #define foo4random() (arc4random() % ((unsigned)RAND_MAX + 1))

Objective-c相关问答推荐

如何从 Cocoa 的 NSDictionary 中获取特定键的值?

跨平台 iPhone/Android 代码共享

将 NSArray 保存到 NSUserDefaults 并在 NSMutableArray 中获取它

如何复制 .xib 文件?

将长按手势和拖动手势结合在一起

判断是否显示 UIAlertView

NSMutableDictionary 线程安全

iOS - UITableViewCell 中 UIButton 的延迟Touch Down事件

Select 时如何更改 UITableViewCell 的 colored颜色 ?

进入编辑模式时动画自定义绘制的 UITableViewCell

Objective-C 中是否有一些文字字典或数组语法?

如何从 CGPoint 和 CGSize 创建 CGRect?

NSManagedObjectContext:异常断点在 save: 方法处停止,但没有日志(log)/崩溃/错误

UIBezierPath 减go 路径

如何在 Objective-C (iOS) 中判断 NaN 值

Core Data使用原始数据类型的标量属性复选框

在 UITableView 中更改复选标记的 colored颜色

Objective-c - CABasicAnimation 在动画后应用更改?

更改 UITextField 占位符字体

Objective-C in,out,inout,byref,byval, .. 等等.这些是什么?