std::rand
來自 cppreference.com
定義於標頭檔案 <cstdlib> |
||
int rand(); |
||
返回一個範圍為 [
0,
RAND_MAX]
的偽隨機整數值。
std::srand() 為 rand()
使用的偽隨機數生成器播種。如果在呼叫任何 std::srand() 之前使用 rand()
,則 rand()
的行為如同已用 std::srand(1) 播種。
每次用 std::srand() 為 rand()
播種後,它在後續呼叫中必須生成相同的值序列。
標準庫中的其他函式可能會呼叫 rand
。哪些函式這樣做是實現定義的。
rand()
是否執行緒安全是實現定義的。
目錄 |
[編輯] 返回值
介於 0 和 RAND_MAX 之間的偽隨機整數值。
[編輯] 注意
不保證生成的隨機序列的質量。過去,rand()
的一些實現存在嚴重的隨機性、分佈和序列週期缺陷(在一個著名的例子中,低位簡單地在呼叫之間在 1 和 0 之間交替)。
不建議將 rand()
用於需要高質量隨機數生成的場合。建議使用 C++11 的隨機數生成功能來替換 rand()
。(C++11 起)
[編輯] 示例
下面的函式 bounded_rand()
是 Debiased Modulo (Once) 的改編版本。
執行此程式碼
#include <cstdlib> #include <ctime> #include <initializer_list> #include <iostream> unsigned bounded_rand(unsigned range) { for (unsigned x, r;;) if (x = rand(), r = x % range, x - r <= -range) return r; } int main() { std::srand(std::time({})); // use current time as seed for random generator const int random_value = std::rand(); std::cout << "Random value on [0, " << RAND_MAX << "]: " << random_value << '\n'; for (const unsigned sides : {2, 4, 6, 8}) { std::cout << "Roll " << sides << "-sided die 8 times: "; for (int n = 8; n; --n) std::cout << 1 + bounded_rand(sides) << ' '; std::cout << '\n'; } }
可能的輸出
Random value on [0, 2147483647]: 948298199 Roll 2-sided die 8 times: 2 2 1 2 1 1 2 2 Roll 4-sided die 8 times: 1 3 4 2 1 3 3 1 Roll 6-sided die 8 times: 3 2 1 6 6 4 4 2 Roll 8-sided die 8 times: 4 5 6 6 3 6 1 2
[編輯] 參閱
(C++11) |
產生在給定範圍內均勻分佈的整數值 (類模板) |
為偽隨機數生成器播種 (函式) | |
由 std::rand 生成的最大可能值 (宏常量) | |
在指定範圍內生成隨機整數 (函式模板) | |
C 文件 用於 rand
|