我有以下输入(由 NSLog 验证)xleft = 128, xRight = 192
:. 下一行代码使用这些 -
xPos = (arc4random() % xRight-xleft) + xleft;
在最后一次运行时,xPos = 53。根据我的计算,如果产生的随机数为零,它应该不小于 128 (192 - 128 = 64, rand(64) = 0, 0 + 128 = 128
。我正在尝试生成 xLeft 到 xRight 范围内的随机数。
我有以下输入(由 NSLog 验证)xleft = 128, xRight = 192
:. 下一行代码使用这些 -
xPos = (arc4random() % xRight-xleft) + xleft;
在最后一次运行时,xPos = 53。根据我的计算,如果产生的随机数为零,它应该不小于 128 (192 - 128 = 64, rand(64) = 0, 0 + 128 = 128
。我正在尝试生成 xLeft 到 xRight 范围内的随机数。
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
% 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:
So you should expect anything in the range [0, xRight)