开发者

How do you generate a random number within a given limit using the ActionScript?

How do you generate a random开发者_StackOverflow社区 number within a given limit using the ActionScript? Suppose the limit is 1-100. Can you Answer me the explanation too

I want to something put in the twitter or facebook, it wil just moves up n down (i.e moving the placing the object).. For that we need to generate the random numbers r8


So if I understand well, you want something like a next(low, high) method. AS3 contains already a Math.random() method what generates a floating point random number from 0 to 1.

In order to restrict it, you need to do something like this:

var low:Number = 1;
var high:Number= 100;
var result:Number = Math.floor(Math.random() * (1 + high - low)) + low;

The code is quite straightforward, basically you're multiplying the difference between high & low and adding the low. Overall result is floored using Math.floor() to be sure it's an integer.

Hope it helps!


To get a number from 0 to 100, you can use:

Math.random()*100;

To get a number from from 10 to 110 use:

Math.random()*100 + 10;


Just in case someone needs Kel answer wrapped in a Flex Random number generator for a range of values

    public function Random(min:int, max:int):int
    {
        var resp:int ;

        resp = Math.floor(Math.random() * (1 + max - min)) + min;

        return resp ;               
    }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜