當前位置:
首頁 >
C++ 随机函数
發(fā)布時間:2023/12/16
36
豆豆
1.產生隨機數(shù):
? ?rand():內部實現(xiàn)是用線性同余法做的,它不是真的隨機數(shù),因其周期特別長,故在一定的范圍里可看成是隨機的。
? ? ? ? ? ? ? ? ?rand()返回一隨機數(shù)值的范圍在0至RAND_MAX 間。RAND_MAX的范圍最少是在32767之間(int)。
? ? ? ? ? ? ? ? ?所在的頭文件:#include <cstdlib> // 標準庫
?
實現(xiàn)代碼:
#include <iostream>#include <cstdlib> // 標準庫using namespace std;int main(int argc, const char * argv[]) {cout << rand() << endl;cout << rand() << endl;return 0;}運行結果:
?
2.如果沒加srand()初始化隨機數(shù)發(fā)生器,會發(fā)現(xiàn)rand雖然產生了隨機數(shù),但是重復運行會發(fā)現(xiàn)隨機數(shù)
? ?不會變。同樣是下面對應的兩個數(shù)。用戶未設定隨機數(shù)種子時,系統(tǒng)默認的隨機數(shù)種子為1。
?
3.srand()初始化:rand()產生的是偽隨機數(shù)字,每次執(zhí)行時是相同的;若要不同,用函數(shù)srand()初始化它。
? 語法:void?srand(unsigned? int? seed);??
? 所在頭文件:cstdlib
? 參數(shù)seed必須是個整數(shù),通常可以利用time(0)的返回值或NULL來當做seed。
#include <iostream>#include <cstdlib> // 標準庫#include <ctime>using namespace std;int main(int argc, const char * argv[]) {srand((unsigned)time(NULL));cout << rand() << endl;return 0;}運行結果:
?
總結
- 上一篇: 对于超前,滞后,超前滞后使用范围
- 下一篇: qq大厅连连看外挂:c++实现