2011-04-09 146 views
23

我想要獲得一個在iPhone上工作的隨機數生成器。有兩個文本字段標籤和一個按鈕。在一個文本框中輸入最小數量,然後在下一個文本框中輸入最大數量點擊按鈕將顯示UILabel中的隨機數。我之前做過這件事,今天不能爲我的生活弄清楚。我可以訪問的任何代碼或地方發現這將是太棒了。在iOS中生成範圍內的隨機數?

感謝

回答

94
NSString *min = myMinTextField.text; //Get the current text from your minimum and maximum textfields. 
NSString *max = myMaxTextField.text; 

int randNum = rand() % ([max intValue] - [min intValue]) + [min intValue]; //create the random number. 

NSString *num = [NSString stringWithFormat:@"%d", randNum]; //Make the number into a string. 

[myLabel setText:num]; // Give your label the value of the string that contains the number. 

更新:

看來,它可能是更好的使用arc4random而不是rand你可以看到更多關於它here。只需更換所有rand s與arc4random

+0

我記得現在!這正是我做到的。感謝百萬 – Frankrockz 2011-04-09 00:34:50

+10

我使用'arc4random()'來產生隨機數。只是我2美分。 – 2011-04-09 00:53:38

+0

我似乎無法讓arc4random爲我工作。不知道爲什麼。無論如何非常感謝 – Frankrockz 2011-04-09 02:53:42

23
#include <stdlib.h> 

int randomNumber = min + rand() % (max-min); 
相關問題