How to create a random float in Objective-C?

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

    I ended up generating to integers one for the actual integer and then an integer for the decimal. Then I join them in a string then I parse it to a floatvalue with the "floatValue" function... I couldn't find a better way and this works for my intentions, hope it helps :)

    int integervalue = arc4random() % 2;
    int decimalvalue = arc4random() % 9;   
    NSString *floatString = [NSString stringWithFormat:@"%d.%d",integervalue,decimalvalue];
    float randomFloat = [floatString floatValue];
    

提交回复
热议问题