24

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

Frankrockz
  • 594
  • 1
  • 6
  • 24

2 Answers2

97
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

Community
  • 1
  • 1
Dair
  • 15,910
  • 9
  • 62
  • 107
  • I remember now! That was exactly how I did it. Thanks a million – Frankrockz Apr 09 '11 at 00:34
  • 10
    I perfer `arc4random()` for generating random numbers. Just my 2 cents. – Simon Goldeen Apr 09 '11 at 00:53
  • I couldn't seem to get arc4random to work for me. Don't know why. Anyhow thanks so much – Frankrockz Apr 09 '11 at 02:53
  • 1
    This code is working properly to generate random numbers between a range but it is not displaying last number. Means between range (1 to 50 ) it is showing numbers between 1 to 49. – Himanshu Mahajan Nov 26 '12 at 07:04
  • 5
    @HimanshuMahajan: If you want the range to be inclusive: `([max intValue] - [min intValue]+1) + [min intValue]` – Dair Nov 27 '12 at 00:16
  • Or just rand() % ([max intValue] would be enough (no need of subtracting and adding the same variable) – Gokul Mar 05 '15 at 09:36
  • @Gokul: Your reasoning is incorrect. Notice the parentheses. `rand() % ([max inValue] - [min intValue])` generates a range from 0 to the "distance" of max and min. Then you shift this upward by the minimum value. – Dair Mar 05 '15 at 18:30
  • I stand corrected :) – Gokul Mar 06 '15 at 05:38
  • So glad this immediately closed question is so useful... and still alive! :-) Thanks Dair (and for the recent clairifications) – eric Jun 04 '15 at 00:39
24
#include <stdlib.h>

int randomNumber = min + rand() % (max-min);
Peter DeWeese
  • 18,141
  • 8
  • 79
  • 101