Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random number in range in iOS? [closed]

Tags:

I'm trying to get a random number generator working on the iPhone. There are two text fields a label and a button. Enter the minimum number in one textfield and the maximum in the next. Clicking the button will display the random number in the UILabel. I did this once before and can't figure it out for the life of me today. Any code or places I could visit to find this out would be fantastic.

Thanks

like image 272
Frankrockz Avatar asked Apr 09 '11 00:04

Frankrockz


People also ask

How do you generate a random number from within a range?

Method 1: Using Math. random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). This random number can then be scaled according to the desired range.

How do you generate a random number in a range in Swift?

To generate a random number in Swift, use Int. random() function. Int. random() returns a number, that is randomly selected, in the given range.


1 Answers

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. 

Update:

It appears that it is probably better to use arc4random as opposed to rand you can see more about it here. Just replace all the rands with arc4random

like image 115
Dair Avatar answered Sep 21 '22 06:09

Dair