问题
Looking to find how I would format a call to arc4Random()
to use a range of numbers from -10 to 10.
Or does arc4Random()
only generate from 0 to X? If that's the case I will need to manipulate the result from arc4Random()
so that it may be a result within the specified range?
回答1:
arc4random
returns a u_int32_t
, which is an unsigned type. You need to cast it to a signed type and then subtract.
I assume you want a number from -10 to +10 inclusive (you want both -10 and +10 to be chosen sometimes).
If you are targetting iOS 4.3 or later, or Mac OS X 10.7 or later, you should use the arc4random_uniform
function:
int myNumber = (int)arc4random_uniform(21) - 10;
If you are targetting an older OS, you have to use arc4random
:
int myNumber = (int)(arc4random() % 21) - 10;
来源:https://stackoverflow.com/questions/9552486/arc4random-range-including-negatives