How to create a random float in Objective-C?

前端 未结 8 1470
清酒与你
清酒与你 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: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 = ;
    
    float r = 0.3 * (0.5 + arc4random_uniform(upper_bound)*1.0/upper_bound/2);
    

提交回复
热议问题