1. 程式人生 > >生成一定範圍內的隨機數

生成一定範圍內的隨機數

生成方法如下:

+(NSInteger)getRandomNumber:(NSInteger)from to:(NSInteger)to

{
    //eg:[1,10) 包含 1,不包含10;
    return (NSInteger)(from + (arc4random() % (to - from + 1)));

}

Objective-C 中有個arc4random()函式用來生成隨機數且不需要種子,但是這個函式生成的隨機數範圍比較大,需要用取模的演算法對隨機值進行限制,有點麻煩。
其實Objective-C有個更方便的隨機數函式arc4random_uniform(x),可以用來產生0~(x-1)範圍內的隨機數,不需要再進行取模運算。如果要生成1~x的隨機數,可以這麼寫:arc4random_uniform(x)+1。

+(NSInteger)getRandomNumber:(NSInteger)from to:(NSInteger)to

{
    //eg:[1,10) 包含 1,不包含10;
    return (NSInteger)(arc4random_uniform(to-from)+from);

}