How to create a random float in Objective-C?

2019-01-31 18:34发布

I'm trying to create a random float between 0.15 and 0.3 in Objective-C. The following code always returns 1:

int randn = (random() % 15)+15;
float pscale = (float)randn / 100;

What am I doing wrong?

8条回答
SAY GOODBYE
2楼-- · 2019-01-31 19:07

Here is a function

- (float)randomFloatBetween:(float)smallNumber and:(float)bigNumber {
float diff = bigNumber - smallNumber;
return (((float) (arc4random() % ((unsigned)RAND_MAX + 1)) / RAND_MAX) * diff) + smallNumber;
}
查看更多
聊天终结者
3楼-- · 2019-01-31 19:09

Try this:

 (float)rand() / RAND_MAX

Or to get one between 0 and 5:

 float randomNum = ((float)rand() / RAND_MAX) * 5;

Several ways to do the same thing.

查看更多
登录 后发表回答