2012-05-02 31 views
3

我在我的iOS應用程序生成的隨機值的函數調用arc4random從-5到6爲什麼arc4random返回古怪的值?

double num; 
for (int i = 0; i < 3; i++) { 
    num = (arc4random() % 11) - 5; 
    NSLog(@"%0.0f", num); 
} 

我從控制檯下面的輸出。

2012-05-01 20:25:41.120 Project32[8331:fb03] 0 
2012-05-01 20:25:41.121 Project32[8331:fb03] 1 
2012-05-01 20:25:41.122 Project32[8331:fb03] 4294967295 

0和1是範圍內的值,但是wowww,4294967295從哪裏來?

arc4random()更改爲rand()修復了這個問題,但rand()當然需要播種。

+1

您能否顯示'num'的聲明?可能但可能只是一個'unsigned int'? :) – nacho4d

+1

我猜數字是一個無符號整數? – lnafziger

+1

對不起,我只包含了num的聲明。 –

回答

7

arc4random()返回u_int32_t - 這是一個無符號整數,一個並不代表負值。每當arc4random() % 11出現一個數字0≤n < 5,你減去5並回到一個非常大的數字。

double s 可以代表負數,當然,但您不會轉換爲double,直到爲時已晚。在該處粘貼一個演員表:

num = (double)(arc4random() % 11) - 5; 

在減法之前促進模的結果,一切都會好起來的。

+0

謝謝!這就說得通了。 'arc4random()'返回一個無符號整數,可以用減法溢出。 –

4

使用

arc4random_uniform(11) - 5; 

,而不是嘗試。

從手冊頁:

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

謝謝,什麼是「模數偏差」? –

+0

@JustinCase:假設一個隨機數發生器只產生數字1到5.如果你有'rand()%2',你更可能得到1而不是0。這就是* modulo bias *。很顯然,'arc4_random()%upper_bound'(其中'upper_bound'不是2的冪)的偏見並不像我的例子那麼大,但它仍然存在。 – dreamlax

+0

此頁面也有一個示例 - http://romhack.wikia.com/wiki/Random_number_generator – danielbeard