How to create a random float in Objective-C?

前端 未结 8 1500
清酒与你
清酒与你 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:28

    Your code works for me, it produces a random number between 0.15 and 0.3 (provided I seed with srandom()). Have you called srandom() before the first call to random()? You will need to provide srandom() with some entropic value (a lot of people just use srandom(time(NULL))).

    For more serious random number generation, have a look into arc4random, which is used for cryptographic purposes. This random number function also returns an integer type, so you will still need to cast the result to a floating point type.

提交回复
热议问题