开发者

Arc4random float?

Doing this:

float x = arc4random() % 100;

returns a decent result of a number between 0 and 100.

But doing this:

float x = (arc4random() % 100)/100;

Returns 0. How can I get it to 开发者_JAVA百科return a float value?


Simply, you are doing integer division, instead of floating point division, so you are just getting a truncated result (.123 is truncated to 0, for example). Try

float x = (arc4random() % 100)/100.0f;


You are dividing an int by an int, which gives an int. You need to cast either to a float:

float x = (arc4random() % 100)/(float)100;

Also see my comment about the modulo operator.


To get a float division instead of an integer division:

float x = arc4random() % 100 / 100.f;

But be careful, using % 100 will only give you a value between 0 and 99, so dividing it by 100.f will only produce a random value between 0.00f and 0.99f.

Better, to get a random float between 0 and 1:

float x = arc4random() % 101 / 100.f;

Even better, to avoid modulus bias:

float x = arc4random_uniform(101) / 100.f;

Alternatively, to avoid a two digits precision bias:

float x = (float)arc4random() / UINT32_MAX;

And in Swift 4.2+, you get built-in support for ranges:

let x = Float.random(in: 0.0...1.0)


In Swift:

Float(arc4random() % 100) / 100
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜