C++ Random 的使用
阿新 • • 發佈:2018-09-25
ostream pan for clu alt ref blog cin ios
1、rand() 方法
rand()不需要參數,它會返回一個從0到最大隨機數的任意整數,最大隨機數的大小通常是固定的一個大整數。 這樣,如果你要產生0~10的10個整數,可以表達為:
int N = rand () % 11;
|
這樣,N的值就是一個0~10的隨機數,如果要產生1~10,則是這樣:
int N = 1 + rand () % 10;
|
總結來說,可以表示為:
a + rand () % n
|
2、random庫使用
#include <iostream> #include<random> using std::cout; using std::endl; using std::default_random_engine; int main() { default_random_engine e; for (size_t i = 0; i < 10; ++i) //生成十個隨機數 cout << e() << endl; cout << "Min random:" << e.min() << endl; //輸出該隨機數引擎序列的範圍 cout << "Max random:" << e.max() << endl; return 0; }
--修改隨機種子
#include <iostream> #include <random> using std::cout; using std::endl; using std::default_random_engine; int main() { default_random_engine e; //或者直接在這裏改變種子 e(10)e.seed(10); //設置新的種子 for (size_t i = 0; i < 10; ++i) cout << e() << endl; cout << "Min random:" << e.min() << endl; cout << "Max random:" << e.max() << endl; return 0; }
參考 :
https://www.cnblogs.com/byhj/p/4149467.html
http://www.cplusplus.com/reference/random/?kw=random
C++ Random 的使用