2011-04-21 22 views
0

在objective-c中有一種方法可以讓你僞隨機地決定兩個整數嗎?還是有一個快速的方法來實現這一點?在2個定義的整數之間隨機選取

+1

有關在Objective-C的隨機數的詳細討論(!包括爲什麼你不應該使用蘭特)查看http://stackoverflow.com/questions/ 160890 /產生隨機號碼功能於目標c。 – 2011-04-21 08:55:53

回答

4

使用以下:

int number = arc4random() % 2; 
if(number==0){ 
    //pick one number 
}else{ 
    //pick other number 
} 
+0

稍微好看的是使用三元運算符。 +1雖然。 – taskinoor 2011-04-21 09:08:35

+0

這是一個無用的沉重計算。爲什麼選擇arc4?沒有簡單的隨機返回0和0之間的浮點數,(9)在ObjC中? – 2011-04-25 11:38:54

0

in C++ that would be result = rand() < 0.5 ? int1 : int2 爲什麼你不能在ObjC中建立相同的命令?

+0

這也可以在Objective中起作用。 – Konrad77 2011-04-21 08:55:55

+1

這將幾乎總是返回int2,除非rand()返回0. – taskinoor 2011-04-21 08:57:05

+0

爲什麼? rand()返回浮點數。可能是Linux特有的?無論如何,我認爲很容易弄清楚這個代碼的含義。 – 2011-04-22 05:26:17

2
randomSelection = arc4random() % 2 ? choice1 : choice2;