开发者

How to generate a random float number in Objective-C with min and max? [duplicate]

开发者 https://www.devze.com 2023-03-06 18:36 出处:网络
This questio开发者_StackOverflown already has answers here: Closed 11 years ago. Possible Duplicates:
This questio开发者_StackOverflown already has answers here: Closed 11 years ago.

Possible Duplicates:

Generating Random Numbers in Objective-C

What's the most optimal way to get a random floatingpoint number between floatA and floatB?

Hi,

I want to generate a random float number like

float scale = randFloat(0.5f, 2.0f);

How do I do this in objective-c?


Here is how you generate them :

// Get random value between 0 and 99
int x = arc4random() % 100;

// Get random number between 500 and 1000
int y =  (arc4random() % 501) + 500);

You can easily extend this for any range you need.

Hope that helps.


Generate two random integers and divide one by the other. With some manipulation you can introduce a range.

Also, depending on the required resolution you could simply generate a single random integer and divide it by a fixed integer to get your float. For example, generate a random number between 0 and 100,000 and divide it by 100,000. You can offset and shift the result around to get the range you need.

0

精彩评论

暂无评论...
验证码 换一张
取 消