objective-c - 两个 float 之间的随机数生成

标签 objective-c random floating-point

我试图在两个 float 之间生成一个随机数(最大值增加一半)

这是我目前所拥有的,但它不起作用

    //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);

最佳答案

包括:

#define ARC4RANDOM_MAX 0x100000000

然后试试这个:

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

关于objective-c - 两个 float 之间的随机数生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6528988/

相关文章:

c# - 为什么 System.Random 连续多次给出 '1',然后一段时间没有,然后又一次?

c++ - boost::variate_generator 语法错误

R:如何从每一列和 Bootstrap 中随机采样一个值

java - Objective C 到 Java : converting a typedef block

iphone - NSXMLParser 因 & 符号而阻塞

iphone - Objective-C 的单元测试和代码覆盖框架?

c++ - 如何通过按位运算在 double 之间执行求和

c# - 增加 float 的第 n 位数字

java - 表中异常的 float

objective-c - Apple 模板在转换为 BOOL 后是否包含错误?