English 中文(简体)
Xcode arc4random() not behav as expected
原标题:Xcode arc4random() not behaving as expected

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.

最佳回答

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.

参考资料:

问题回答

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

因此,对这一表述的评价是:

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

因此,你应期望在[0、x 权利]范围内出现任何情况。





相关问题
How to change out-of-focus text selection color in Xcode?

Okay, I ll bite. I ve got really pleasant code/window colors set up in Xcode. Ordinarily, my selection color is very visible. When I am doing a project search and iterating through the results, ...

Iphone NSTimer Issue

Hi I am new to objective c. I am trying to make an app for iphone. I have a button on my view, and the click on which the function playSound is called. This is working properly. It does plays the ...

Include a .txt file in a .h in C++?

I have a number of places where I need to re-use some template code. Many classes need these items In a .h could I do something like: #include <xxx.txt> and place all of this code in the ....

Iterating over string/strlen with umlauted characters

This is a follow-up to my previous question . I succeeded in implementing the algorithm for checking umlauted characters. The next problem comes from iterating over all characters in a string. I do ...

Xcode open two editor windows with same file

Is it possible to open the same file in two separate windows in Xcode. I can open a file in one window and the same file in the main Xcode editor window, but I wanted two separate fulltime editor ...

Forcing code signing refresh in Xcode

In our environment, we share resources across multiple projects and platforms. When building for iPhone, only a subset of those resources are needed. Since that subset is still considerable, we have ...

热门标签