arc4random() range including negatives

余生颓废 提交于 2019-11-30 17:40:27

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!