How to create a random float in Objective-C?

前端 未结 8 1434
清酒与你
清酒与你 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.

    0 讨论(0)
  • 2020-12-24 06:30

    Easiest.

    + (float)randomNumberBetween:(float)min maxNumber:(float)max
    {
        return min + arc4random_uniform(max - min + 1);
    }
    
    0 讨论(0)
  • 2020-12-24 06:31

    Here is a function

    - (float)randomFloatBetween:(float)smallNumber and:(float)bigNumber {
        float diff = bigNumber - smallNumber;
        return (((float) (arc4random() % ((unsigned)RAND_MAX + 1)) / RAND_MAX) * diff) + smallNumber;
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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];
    
    0 讨论(0)
  • 2020-12-24 06:46

    Try this:

     (float)rand() / RAND_MAX
    

    Or to get one between 0 and 5:

     float randomNum = ((float)rand() / RAND_MAX) * 5;
    

    Several ways to do the same thing.

    0 讨论(0)
提交回复
热议问题