有時(shí)候我們需要在程序中生成隨機(jī)數(shù)鳞陨,但是在Objective-c中并沒(méi)有提供相應(yīng)的函數(shù)颠猴,好在C中提供了rand()、srand()坡贺、random()官辈、arc4random()幾個(gè)函數(shù)。那么怎么使用呢遍坟?下面將簡(jiǎn)單介紹:
1拳亿、? 獲取一個(gè)隨機(jī)整數(shù)范圍在:[0,100)包括0,不包括100
int x = arc4random() % 100;
2愿伴、? 獲取一個(gè)隨機(jī)數(shù)范圍在:[500,1000)肺魁,包括500,包括1000
int y = (arc4random() % 501) + 500;
3隔节、? 獲取一個(gè)隨機(jī)整數(shù)鹅经,范圍在[from,to),包括from怎诫,包括to
-(int)getRandomNumber:(int)from to:(int)to
{
return (int)(from + (arc4random() % (to – from + 1)));
}