乱数を生成する方法

1072 ワード

C/C++では、乱数を生成するにはrand()関数とsrand()関数を使用します.
rand()関数は0~RAND_を返しますMAX(32767)の整数.
  • 乱数を発生する、範囲
  • を設定しない.
    #include 
    using namespace std;
    
    int main()
    {
    	int n = rand();
    	cout << n << endl;
    	return 0;
    }
    
  • は、対応する範囲内の乱数
  • を生成する.
    #include 
    using namespace std;
    
    int main()
    {
    	// [0,99]
    	int n = rand()%100;
    	cout << n << endl;
    	return 0;
    }
    

    srand()関数はrand()関数のシードを設定するために使用されます.異なるパラメータに基づいて異なる種子を生成する.rand()関数のみを使用する場合のデフォルトのシードは1なので、次回アクセスするときは初めて発生する乱数の値です.
    srand()    : void srand (unsigned int seed);
    

    乱数は一般に種子として時間を用いるが,時間が変化し続けるためtime()関数を用いる必要がある.
    time()    : time_t time(time_t *t);
    

    time()関数に必要なヘッダファイルはincludeです
    #include 
    #include  
    using namespace std;
    int main()
    {
    	srand(time(NULL));
    	//srand((int)time(0));
    	for(int i = 0; i < 20; i++)
    		cout << rand() << endl;
    	system("pause");
    	return 0;
    }