1

我有以下输入(由 NSLog 验证)xleft = 128, xRight = 192:. 下一行代码使用这些 -

xPos = (arc4random() % xRight-xleft) + xleft;

在最后一次运行时,xPos = 53。根据我的计算,如果产生的随机数为零,它应该不小于 128 (192 - 128 = 64, rand(64) = 0, 0 + 128 = 128。我正在尝试生成 xLeft 到 xRight 范围内的随机数。

4

2 回答 2

2

Try:

xPos = (arc4random() % (xRight-xleft)) + xleft; 

Basically you're modding by xRIght and then subtracting xleft, instead of first subtracting xleft from xright and modding with the result.

Reference link: http://www.techotopia.com/index.php/Objective-C_2.0_Operator_Precedence

于 2012-01-13T22:19:21.400 回答
2

% has higher precedence in C and directly derived languages like Objective-C than + and -. It's equal to * and /.

So that expression is evaluated as:

  1. Get arc4random
  2. Get the modulus of that and xRight
  3. Subtract xLeft
  4. Add xLeft

So you should expect anything in the range [0, xRight)

于 2012-01-13T22:21:35.147 回答