srand() - rand() 関数のシードの設定

標準

標準/拡張機能 C/C++ 依存項目

POSIX.1
XPG4
XPG4.2
Single UNIX Specification、バージョン 3

両方  

形式

#include <stdlib.h>

void srand(unsigned int seed);

機能説明

srand() は、その引数 seed を、疑似乱数の 新しいシーケンスの seed として使用し、以後の rand() への呼び出しによって 戻ります。srand() が呼び出されない場合には、srand(1) が プログラムの開始で呼び出されたときのように、rand() シードが設定されます。seed のその他のどの値も、生成プログラムを異なる開始点に設定します。rand() 関数は、疑似乱数を生成します。

乱数のランダム・シーケンスを確実なものにする方法として、time() 関数の戻り値 を、srand() の引数として使用することもできます。

戻り値

srand() は、値を戻しません。

CELEBS31
⁄* 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

関連情報