Random Number Problem in Objective-C

I am trying to create 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.0000000

+3
source share
6 answers

Try this instead:

int randomNum = arc4random() % ([items count] +1);

note that randomNumit will not be used as an array reference. For this you want:

int randomRef = arc4random() % [items count];
id myRandomObject = [myArray objectAtIndex:randomRef];

arc4random()returns u_int32_t(int), which makes it easy to transfer to things like bones, arrays and other problems of the real world, unlikerand()

+5
source

randomNum is always 0.0000000

This is because you are 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 is one way to fix this:

float randomNum = ((float)rand() / (float)RAND_MAX) * [items count];

arc4random.

+6

, 0 , :

randomNum = random() % [items count];  // between 0 and arraySize-1


If you want your array size to include:

randomNum = random() % ([items count]+1);  // between 0 and arraySize
+2
source

Try rand() * [items count];

IIRC, rand()returns values ​​from 0 to 1.

+1
source

people say arc4random () is the best rnd method ...

you can use it this way to get a number in the 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
+1
source

Before using rand (), you must set the seed, you do this by calling the srand function and passing the seed.

See here for srand documentation and here for rands.

0
source

Source: https://habr.com/ru/post/1794972/


All Articles