c++獲得隨機數和指定區間隨機數(筆記)
阿新 • • 發佈:2021-02-19
srand()函式是隨機數發生器的初始化函式
rand()
關於隨機數生成器,有兩個相關的函式。一個是 rand(),該函式只返回一個偽隨機數。生成隨機數之前必須先呼叫 srand() 函式。
srand()需要提供一個種子,這個種子會對應一個隨機數,如果使用相同的種子後面的rand()函式會出現一樣的隨機數。如: srand(1); 直接使用 1 來初始化種子。不過為了防止隨機數每次重複,常常使用系統時間來初始化,即使用 time 函式來獲得系統時間,它的返回值為從 00:00:00 GMT, January 1, 1970 到現在所持續的秒數,然後將 time_t 型資料轉化為(unsigned)型再傳給 srand 函式,即: srand((unsigned) time(&t));
例:
#include<iostream> #include<ctime> using namespace std; int main() { int i, j; srand((unsigned)time(NULL)); for (i = 0; i < 10; i++) { j = rand(); cout << "隨機數:" << j << endl; } return 0; }
結果:
生成指定[m,n]區間的隨機數
使用 rand() 和 srand() 產生指定範圍內的隨機整數的方法:“模除+加法”的方法。如要產生 [m,n] 範圍內的隨機數 num,可用:int num=rand()%(n-m+1)+m;(即 rand()%[區間內數的個數]+[區間起點值])
例:生成介於100到200之間的隨機數
#include<iostream> #include<ctime> using namespace std; int main() { int i, m, n; m = 100; n = 200; srand((unsigned)time(NULL)); for (i = 0; i < 10; i++) { int num = rand() % (n-m+1) + m; cout << "隨機數:" << num << endl; } return 0; }
結果: