1. 概述
本文講述 rand,srand,以及產生固定範圍內的隨機數。
2. rand 函數
可以使用 <stdlib.h> 頭文件中的 rand() 函數來生成隨機數,隨機生成一個位於 0 ~ RAND_MAX 之間的整數。它的用法如下:
int rand ();
爲什麼不使用 random() 函數?
具體用例:
#include <stdio.h>
#include <stdlib.h>
int main(){
int randnum = rand();
printf("%d\n", randnum);
return 0;
}
在我的虛擬機上顯示的結果是
1804289403
我的虛擬機版本如下
$ cat /proc/version
Linux version 4.18.0-20-generic (buildd@lcy01-amd64-020)
(gcc version 7.3.0 (Ubuntu 7.3.0-16ubuntu3))
#21~18.04.1-Ubuntu SMP Wed May 8 08:43:37 UTC 2019
3. 隨機種子 srand 函數
rand() 函數產生的隨機數是僞隨機數,是根據一個數值按照某個公式推算出來的,這個數值我們稱之爲“種子”。因此在每次計算機啓動的時候,種子被確定,所以 rand() 算出來的值就是固定的。
爲什麼重啓計算機就固定了呢?這其中到底有什麼樣的機制?
如何改變種子?使用 srand 函數,用法如下:
void srand (unsigned int seed);
實例如下:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int testsrand;
srand((unsigned)time(NULL));
testsrand = rand();
printf("%d\n", testsrand);
return 0;
}
4. 產生固定範圍內的隨機數
我們經常需要產生給定範圍內的隨機數。那怎樣才能做到呢?其實很簡單,只需要藉助取模和加法即可。
想象一下,假如我們需要從範圍 [a, b] 的隨機數 y。底線就是 a。即 x >= a。因此結果變成:
y = r % x + a
因此我們將目光聚焦於 (b - a),rand() 產生的結果 r ,r 對 x 取模的最大值爲 (b - a), 因此,x = (b - a + 1)。公式變爲:
y = r % (b - a + 1)+ a
實例如下:
/* 生成 [7, 10] 中的隨機數 */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
int y;
srand((unsigned)time(NULL));
y = rand() % (10 - 7 + 1) + 7;
printf("%d\n",a);
return 0;
}
5. 總結
本文學習了 rand,srand,以及產生固定範圍內的隨機數。
不足之處在於對於一些很深刻的東西,並沒有瞭解得很清楚。希望有機會再去了解。