我试图在两个浮点数之间生成一个随机数(最大值增加一半)
这是我到目前为止所做的,但它不起作用
//range
NSString *minString = [dict objectForKey:@"min"];
float minRange = [minString 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);
答案 0 :(得分:18)
包括:
#define ARC4RANDOM_MAX 0x100000000
然后试试这个:
double val = ((double)arc4random() / ARC4RANDOM_MAX)
* (maxRange - minRange)
+ minRange;
答案 1 :(得分:2)
当然是:
float randomNumber = ((float)arc4random() / ARC4RANDOM_MAX * (maxRange - minRange)) + minRange;