C++ 隨機數與隨機種子數的實例
實現效果圖:

實例代碼:
#include <stdlib.h> #include <iostream> #include <ctime> using namespace std; void Test() {   int ran_num = 0;   cout<<"不指定seed,  ";   for(int i=0; i<10;i++)   {     ran_num = rand()%6;     cout<<ran_num<<" ";   }//每次運行都將輸出:5,5,4,4,5,4,0,0,4,2    srand(1);   cout<<"/n指定seed為1, ";   for(int i=0; i<10;i++)   {     ran_num = rand()%6;     cout<<ran_num<<" ";   }//每次運行都將輸出:5,5,4,4,5,4,0,0,4,2    srand(6);   cout<<"/n指定seed為6, ";   for(int i=0; i<10;i++)   {     ran_num = rand()%6;     cout<<ran_num<<" ";   }//每次運行都將輸出:5,5,4,4,5,4,0,0,4,2   srand((unsigned)time(NULL));   cout<<"/n指定seed當前系統時間, ";   for(int i=0; i<10;i++)   {     ran_num = rand()%6;     cout<<ran_num<<" ";   }//每次運行結果都不一樣 } /* 1.隨機數也隨機種子數之間的關系:隨機種子是用來打亂隨機數的,沒有它,你的隨機數并不是真正隨機 2.種子與結果的關系是:對于不同的種子,有不同的隨機數數列;對于相同的種子,具有相同的隨機數數列 3.一個項目中(可執行文件),就需要設置一次隨機種子 */ int main() {   Test();   return 0; } 感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答
圖片精選