开发者

random number generation between two floats

开发者 https://www.devze.com 2023-03-16 20:22 出处:网络
I am trying to generate a random number between two floats (the max is increased by its half) this is what I have so far but it\'s not working

I am trying to generate a random number between two floats (the max is increased by its half)

this is what I have so far but it's not working

    //range
    NSString *minString = [dict objectForKey:@"min"];
    float minRange = [minStrin开发者_如何转开发g floatValue];
    NSString *maxString = [dict objectForKey:@"max"];
    float maxRange = [maxString floatValue];

    NSLog(@"the ORIGINAL range is %f - %f", minRange, maxRange);

    maxRange = maxRange + (maxRange/2);

    //If you want to get a random integer in the range x to y, you can do that by int randomNumber = (arc4random() % y) + x;

    float randomNumber = (arc4random() % maxRange) + minRange; //ERROR: "Invalid operands to binary expression ('float' and 'float')

    NSLog(@"the range is %f - %f", minRange, maxRange);
    NSLog(@"the random number is %f", randomNumber);


Include:

#define ARC4RANDOM_MAX 0x100000000

And then try this:

double val = ((double)arc4random() / ARC4RANDOM_MAX) 
   * (maxRange - minRange)
   + minRange;


Surely it's:

float randomNumber = ((float)arc4random() / ARC4RANDOM_MAX * (maxRange - minRange)) + minRange;
0

精彩评论

暂无评论...
验证码 换一张
取 消