本文實例講述了C++常見獲取隨機數(shù)的方法。分享給大家供大家參考,具體如下:
方法一:
使用 rand 函數(shù)可以獲取,如下。
#include<iostream>#include<ctime>using namespace std;int main(){ for (int i = 0; i < 10; i++) cout << rand() << endl; return 0;}
隨機數(shù)大小是在0到RAND_MAX,值為2147483647,它是在stdlib中定義的,如果我們希望在某個范圍內(nèi),可以使用 % 結合 / 來實現(xiàn)。
但是不難發(fā)現(xiàn),這里獲得的隨機數(shù)是唯一確定的,而不是變化的。所以,如果我們希望獲得變化的隨機數(shù),可以使用下面的方法。
方法二:
既然使用rand函數(shù)無法獲取到變化的隨機數(shù),這里就可以使用srand來實現(xiàn)了。
#include<iostream>#include<ctime>using namespace std;int main(){ srand(time(0)); for (int i = 0; i < 1000; i++) cout << rand() << endl; return 0;}這里,我們需要引入ctime庫,其中time(0)是獲取從1970年開始的時間(單位:s),然后再獲取rand(),這時的rand就是隨機變化得了。 如下:

但這里獲取的值是不確定的,而如果我們希望獲得在某一范圍內(nèi)的值呢,也很簡單,如下所示:
#include<iostream>#include<ctime>using namespace std;int main(){ srand(time(0)); for (int i = 0; i < 100; i++) cout << rand() % 100 << endl; return 0;}如上,使用求余數(shù)的方法,我們可以獲得0 - 100之間的值。
而如果我們希望得到0 - 1之間的數(shù)呢? 如下所示:
#include<iostream>#include<ctime>using namespace std;int main(){ srand(time(0)); for (int i = 0; i < 100; i++) cout << (rand() % 10) * 0.1 << endl; return 0;}而我們希望得到-1 到 1 之間的數(shù)呢?
#include<iostream>#include<ctime>using namespace std;int main(){ srand(time(0)); for (int i = 0; i < 100; i++) if (i % 2 == 0) cout << (rand() % 10) * 0.1 << endl; else cout << (rand() % 10) * -0.1 << endl; return 0;}上面的程序雖然可以得到正隨機數(shù)和負隨機數(shù),但是是交替出現(xiàn)的,還是不夠隨機,所以我們可以采用下面的方式:
#include<iostream>#include<ctime>using namespace std;int main(){ srand(time(0)); double a; for (int i = 0; i < 100; i++) if (rand() % 10 > 0.4) { cout << (rand() % 10) * 0.1 << endl; } else { a = (rand() % 10) * -0.1; if (a == -0.0) { cout << 0 << endl; } else { cout << a << endl; } } return 0;}這樣,我們就可以得到真正的隨機數(shù)了,后面使用 a == -0.0 判斷是為了防止輸出 -0 的情況。 最終結果如下:

PS:這里再提供幾款相關工具供大家參考使用:
在線隨機數(shù)生成工具:
http://tools.VeVB.COm/aideddesign/rnd_num
在線隨機生成個人信息數(shù)據(jù)工具:
http://tools.VeVB.COm/aideddesign/rnd_userinfo
在線隨機字符/隨機密碼生成工具:
http://tools.VeVB.COm/aideddesign/rnd_password
在線隨機數(shù)字/字符串生成工具:
http://tools.VeVB.COm/aideddesign/suijishu
希望本文所述對大家C++程序設計有所幫助。
新聞熱點
疑難解答