Generating random numbers in Objective-C

前端 未结 13 2464
孤街浪徒
孤街浪徒 2020-11-22 02:07

I\'m a Java head mainly, and I want a way to generate a pseudo-random number between 0 and 74. In Java I would use the method:

Random.nextInt(74)
         


        
13条回答
  •  轮回少年
    2020-11-22 02:36

    This will give you a floating point number between 0 and 47

    float low_bound = 0;      
    float high_bound = 47;
    float rndValue = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);
    

    Or just simply

    float rndValue = (((float)arc4random()/0x100000000)*47);
    

    Both lower and upper bound can be negative as well. The example code below gives you a random number between -35.76 and +12.09

    float low_bound = -35.76;      
    float high_bound = 12.09;
    float rndValue = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);
    

    Convert result to a rounder Integer value:

    int intRndValue = (int)(rndValue + 0.5);
    

提交回复
热议问题