How to create a random float in Objective-C?

前端 未结 8 1435
清酒与你
清酒与你 2020-12-24 06:06

I\'m trying to create a random float between 0.15 and 0.3 in Objective-C. The following code always returns 1:

int randn = (random() % 15)+15;
float pscale =         


        
相关标签:
8条回答
  • 2020-12-24 06:46
    1. use arc4random() or seed your random values
    2. try

      float pscale = ((float)randn) / 100.0f;
      
    0 讨论(0)
  • 2020-12-24 06:49

    Using srandom() and rand() is unsafe when you need true randomizing with some float salt.

    On MAC_10_7, IPHONE_4_3 and higher you can use arc4random_uniform(upper_bound)*. It allows to generate true random integer from zero to *upper_bound*.

    So you can try the following

    u_int32_t upper_bound = <some big enough integer>;
    
    float r = 0.3 * (0.5 + arc4random_uniform(upper_bound)*1.0/upper_bound/2);
    
    0 讨论(0)
提交回复
热议问题