srand()、rand()、time()函數的用法


srand()就是給rand()提供種子seed。

如果srand每次輸入的數值是一樣的,那么每次運行產生的隨機數也是一樣的。

以一個固定的數值作為種子是一個缺點。通常的做法是 :以這樣一句srand((unsigned) time(NULL));來取代,這樣將使得種子為一個不固定的數,這樣產生的隨機數就不會每次執行都一樣了。詳細用法如下:

 1 #include <iostream>
 2 #include <stdlib.h>
 3 #include <time.h>
 4 using namespace std;
 5 int main()
 6 {
 7     /*Seed the random-number generator with current time 
 8     so that the numbers will be different every time we run.*/
 9     srand((unsigned)time(NULL));
10     
11     /* Display 10 numbers */
12     for(int i=0;i<10;i++)
13     {
14         cout<<rand()<<endl;
15     }
16     return 0;
17 }

 

rand(void)用於產生一個偽隨機unsigned int 整數。 
srand(seed)用於給rand()函數設定種子。

srand 和 rand 應該組合使用。一般來說,srand 用於對 rand 進行設置。 
比如:

#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int main()
{
    srand(time(0));
    /* Display 10 numbers */
    for(int i=0;i<10;i++)
    {
        cout<<rand()%100<<endl;
    }
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM