2011-05-31 85 views
8

這樣做:Arc4random float?

float x = arc4random() % 100; 

返回一個數一個體面的結果,從0到100

但是這樣做:

float x = (arc4random() % 100)/100; 

返回0。我怎樣才能得到它返回一個浮動值?

+2

使用'arc4random_uniform(int)'而不是模數構造。看到手冊頁('arc4random(3)')爲什麼。 – 2011-05-31 22:01:53

+0

在4.3中添加了arc4random_uniform。如果可以的話,我也會在下面用這個代替我的答案。 – bensnider 2011-11-02 15:27:29

+0

第一行返回0到99之間的一個整數。 – 2016-01-13 11:04:41

回答

24

簡單地說,你正在做整數除法,而不是浮點除法,所以你只是得到一個截斷的結果(例如.123被截斷爲0)。嘗試

float x = (arc4random() % 100)/100.0f; 
4

你正在用一個int除int,它給出一個int。您需要將其投到浮點數:

float x = (arc4random() % 100)/(float)100; 

另請參閱我對模運算符的評論。

1

要獲得浮部門,而不是一個整數除法:

float x = arc4random() % 100/100.f; 

但要注意,使用% 100只會給你0到99之間的值,因此除以100.f將只產生0.00f和0.99f之間的隨機值。

更好,得到0和1之間的隨機浮動:

float x = arc4random() % 101/100.f; 

更妙的是,爲了避免模偏置:

float x = arc4random_uniform(101)/100.f; 

最佳,以避免精度偏差:

float x = (float)arc4random()/UINT32_MAX; 

我相信斯威夫特會是:

let x = Float(arc4random())/UINT32_MAX