本文介绍了随机数字生成两个花车之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在两个浮点数之间生成一个随机数(最大值增加了一半)这是我迄今为止的,但它不工作
// range
NSString * minString = [dict objectForKey:@min];
float minRange = [minString floatValue];
NSString * maxString = [dict objectForKey:@max];
float maxRange = [maxString floatValue];
NSLog(@ORIGINAL range is%f - %f,minRange,maxRange);
maxRange = maxRange +(maxRange / 2);
//如果你想得到一个在x到y范围内的随机整数,你可以通过int randomNumber =(arc4random()%y)+ x来实现。
float randomNumber =(arc4random()%maxRange)+ minRange; //错误:对二进制表达式无效的操作数('float'和'float')
NSLog(@范围是%f - %f,minRange,maxRange);
NSLog(@random number is%f,randomNumber);
解决方案
#define ARC4RANDOM_MAX 0x100000000
$ p $
然后试试这个:
double val =((double)arc4random ()/ ARC4RANDOM_MAX)
*(maxRange - minRange)
+ minRange;
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 = [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);
解决方案Include:
#define ARC4RANDOM_MAX 0x100000000
And then try this:
double val = ((double)arc4random() / ARC4RANDOM_MAX) * (maxRange - minRange) + minRange;
这篇关于随机数字生成两个花车之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!