iOSの3つの乱数の生成方法について説明します。
iosには次の三つの乱数方法があります。
①rand()とrandowm()は、実際には本物の疑似乱数発生器ではなく、使用前にランダムシードを初期化する必要があります。そうでないと、毎回発生する乱数は同じです。
②arc 4 random()は本物の擬似ランダムアルゴリズムであり、ランダムシードを生成する必要はありません。しかも範囲はランドの二倍です。iPhoneにRAND_MAXは0 x 7 fffffffff(2147483647)であり、arc 4 random()が返した最大値は0 x 10000000000(4294967296)である。
精度比較:arc 4 randowm()>random()>rand()
付:arc 4 randowm()常用方法集合
//
srand((unsigned)time(0)); //
int i = rand() % 5;
//
srandom(time(0));
int i = random() % 5;
//
int i = arc4random() % 5 ;
注:①rand()とrandowm()は、実際には本物の疑似乱数発生器ではなく、使用前にランダムシードを初期化する必要があります。そうでないと、毎回発生する乱数は同じです。
②arc 4 random()は本物の擬似ランダムアルゴリズムであり、ランダムシードを生成する必要はありません。しかも範囲はランドの二倍です。iPhoneにRAND_MAXは0 x 7 fffffffff(2147483647)であり、arc 4 random()が返した最大値は0 x 10000000000(4294967296)である。
精度比較:arc 4 randowm()>random()>rand()
付:arc 4 randowm()常用方法集合
// :[0,100) 0, 100
int x = arc4random() % 100;
// :[500,1000), 500, 1000
int y = (arc4random() % 501) + 500;
// , [from,to), from, to
-(int)getRandomNumber:(int)from to:(int)to
{
return (int)(from + (arc4random() % (to C from + 1)));
}
以上述べましたが、本文の内容は全部です。お好きになってください。