Xcode arc4random() 未按预期运行
我有以下输入(通过 NSLog 验证):xleft = 128,xRight = 192
。下一行代码使用这些 -
xPos = (arc4random() % xRight-xleft) + xleft;
在最后一次运行中,xPos = 53。根据我的计算,如果生成的随机数为零,则它应该不小于 128 (192 - 128 = 64, rand(64) = 0, 0 + 128 = 128
我正在尝试生成 xLeft 到 xRight 范围内的随机数。
I have the following inputs (verified by NSLog): xleft = 128, xRight = 192
. The next line of code uses these-
xPos = (arc4random() % xRight-xleft) + xleft;
On the last run, xPos = 53. By my calculations, it should be no less than 128 if the random number produced is zero (192 - 128 = 64, rand(64) = 0, 0 + 128 = 128
. I am trying to generate random numbers in the range xLeft to xRight.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试:
基本上,您是通过 xRIght 进行修改,然后减去 xleft,而不是先从 xright 中减去 xleft,然后用结果进行修改。
参考链接:http://www.techotopia.com/index.php/Objective- C_2.0_Operator_Precedence
Try:
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
% 在 C 和直接派生语言(如 Objective-C)中比 + 和 - 具有更高的优先级。它等于 * 和 /。
因此,该表达式的计算结果为:
因此,您应该期望 [0, xRight) 范围内的任何内容
% 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)