本文介绍了这个随机函数有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我给它0和400,它返回我有时超过400的值。这是没有意义的。

I give it 0 and 400 and it returns me sometimes values above 400. That doesn't make sense.

- (float)randomValueBetween:(float)low andValue:(float)high {
    return (((float) arc4random() / RAND_MAX) * (high - low)) + low;
}

这实际上是我在网上找到的代码段。

that's actually a snippet I found on the net. Maybe someone can see the bug in there?

推荐答案

表示返回的值可以在 u int32 (即 0至(2 ** 32)-1 )有效范围内的任何位置。这意味着你需要除以 0xFFFFFFFF ,而不是 RAND_MAX ,我想是更少

The manual page for arc4random indicates that the returned value can be anywhere in the range valid for u int32 (i.e. 0 to (2**32)-1). This means you'll want to divide by 0xFFFFFFFF, instead of RAND_MAX, which I would imagine is less (it is library dependant however, so you'll have to check exactly what it is).

您的函数应该成为:

- (float)randomValueBetween:(float)low andValue:(float)high {
    return (((float) arc4random() / 0xFFFFFFFFu) * (high - low)) + low;
}

这篇关于这个随机函数有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 07:07