有時候我們需要在程序中生成隨機數,但是在Objective-c中並沒有提供相應的函數,好在C中提供了rand()、srand()、random()、arc4random()幾個函數。那么怎么使用呢?下面將簡單介紹:
1、 獲取一個隨機整數范圍在:[0,100)包括0,不包括100
int x = arc4random() % 100;
2、 獲取一個隨機數范圍在:[500,1000),包括500,包括1000
int y = (arc4random() % 501) + 500;
3、 獲取一個隨機整數,范圍在[from,to),包括from,包括to
-(int)getRandomNumber:(int)from to:(int)to
{
return (int)(from + (arc4random() % (to – from + 1)));
}