標準/拡張機能 | C/C++ | 依存項目 |
---|---|---|
POSIX.1 |
両方 |
#include <stdlib.h>
void srand(unsigned int seed);
srand() は、その引数 seed を、疑似乱数の 新しいシーケンスの seed として使用し、以後の rand() への呼び出しによって 戻ります。srand() が呼び出されない場合には、srand(1) が プログラムの開始で呼び出されたときのように、rand() シードが設定されます。seed のその他のどの値も、生成プログラムを異なる開始点に設定します。rand() 関数は、疑似乱数を生成します。
乱数のランダム・シーケンスを確実なものにする方法として、time() 関数の戻り値 を、srand() の引数として使用することもできます。
srand() は、値を戻しません。
⁄* CELEBS31
This example first calls &srand. with a value other than 1 to
initiate the random value sequence.
Then the program computes 5 random values for the array of
integers called ranvals.
If you repeat this code exactly, then the same sequence of
random values will be generated.
*⁄
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int i, ranvals[5];
srand(17);
for (i = 0; i < 5; i++)
{
ranvals[i] = rand();
printf("Iteration %d ranvals [%d] = %d¥n", i+1, i, ranvals[i]);
}
}
Iteration 1 ranvals [0] = 24107
Iteration 2 ranvals [1] = 16552
Iteration 3 ranvals [2] = 12125
Iteration 4 ranvals [3] = 9427
Iteration 5 ranvals [4] = 13152