arc4random() range including negatives

后端 未结 1 822
逝去的感伤
逝去的感伤 2021-01-06 12:04

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

相关标签:
1条回答
  • 2021-01-06 12:47

    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;
    
    0 讨论(0)
提交回复
热议问题