Problem randomizing number in Objective-C
I am trying to generate a random number between 0 and the size of my array:
float randomNum = (rand() / RAND_MAX) * [items count];
NSLog(@"%f",randomNum);
NSLog(@"%d",[items count]);
randomNum is always 0.000开发者_运维知识库0000
randomNum is always 0.0000000
That's because you're doing integer division instead of floating-point division; (rand() / RAND_MAX)
will almost always be 0. (Exercise to the reader: when is it not 0?)
Here's one way to fix that:
float randomNum = ((float)rand() / (float)RAND_MAX) * [items count];
You should also be using arc4random instead.
Try this instead:
int randomNum = arc4random() % ([items count] +1);
note that randomNum
won't do as an array reference. To do that, you want:
int randomRef = arc4random() % [items count];
id myRandomObject = [myArray objectAtIndex:randomRef];
arc4random()
returns an u_int32_t
(int) which makes it easily transferrable to stuff like dice, arrays, and other real-world problems unlike rand()
If you want it between 0 and your array size it should be:
randomNum = random() % [items count]; // between 0 and arraySize-1
If you want your array size included:
randomNum = random() % ([items count]+1); // between 0 and arraySize
Try rand() * [items count];
IIRC, rand()
returns values between 0 and 1.
people say that arc4random() is the best rnd method...
you can use it this way to get a number in a range:
int fromNumber = 0;
int toNumber = 50;
float randomNumber = (arc4random()%(toNumber-fromNumber))+fromNumber;
NSLog(@"random number is: %f",randomNumber); // you'll get from 0 to 49
...
int fromNumber = 12;
int toNumber = 101;
float randomNumber = (arc4random()%(toNumber-fromNumber))+fromNumber;
NSLog(@"random number is: %f",randomNumber); // you'll get from 12 to 100
Before using rand() you must set a seed, you do so by calling the srand function and passing a seed.
See here for the srand documentation and here for rand.
精彩评论