How to create a random float in Objective-C?

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

    To add to @Caladain's answer, if you want the solution to be as easy to use as rand(), you can define these:

    #define randf() ((CGFloat)rand() / RAND_MAX)
    #define randf_scaled(scale) (((CGFloat)rand() / RAND_MAX) * scale)
    

    Feel free to replace CGFloat with double if you don't have access to CoreGraphics.

提交回复
热议问题