gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 03:39:34 28 4
gpt4 key购买 nike

我试图在两个 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com