Arc4random () range, including negatives

Look for how I will format the arc4Random() call to use a range of numbers from -10 to 10.

Or arc4Random() only generates from 0 to X? If in this case I need to process the result from arc4Random() so that it can be the result in the specified range?

+4
source share
1 answer

arc4random returns a u_int32_t , which is an unsigned type. You need to give it to the signed type and then subtract it.

I assume that you want a number from -10 to +10 inclusive (you want to be sometimes selected as -10 and +10).

If you configure iOS 4.3 or later or Mac OS X 10.7 or later, you must use the arc4random_uniform function:

 int myNumber = (int)arc4random_uniform(21) - 10; 

If you are targeting an older OS, you should use arc4random :

 int myNumber = (int)(arc4random() % 21) - 10; 
+6
source

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


All Articles