arc4random() 在 iOS 中给出负数

arc4random() gives negative Number in iOS

有时 arc4random() 也会在 objective C.

中给出负数

我的代码如下:

尝试 1:

long ii = arc4random();

尝试 2:

int i = arc4random();

如何才能只得到正数随机数?

谢谢,

不,它总是正数,因为它 returns 一个无符号的 32 位整数 (manpage):

u_int32_t arc4random(void);

您将其视为有符号整数,这是不正确的。

您应该使用 arc4random_uniform() 函数。这是最常用的随机函数。

arc4random_uniform()函数

Returns a random number between 0 and the inserted parameter minus 1. For example arc4random_uniform(3) may return 0, 1 or 2 but not 3.

示例

u_int32_t randomPositiveNo = arc4random_uniform(5) + 1; //to get the range 1 - 5