C語言隨機數使用方法


隨機數在編程中還是有所應用,最近從網上學習到這方面一點知識,想把它寫下來。
一、使用隨機數所需要的頭文件和函數:
        頭文件:cstdlib(C++ 的 standard libraray)    ctime
        函數:    rand()       srand(int seed);   time(NuLL);
二、隨機數的的理解:
       隨機數不是真的隨機數,它是通過公式(有很多)計算出來的。它就像函數一樣——srand(seed)中的seed好比自變量x,而rand()則是seed對應的因變量的值。
       換句話來說,如果seed值固定,那么產生的隨機數也不變。 代碼如下:
代碼如下:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
    srand(1);
    for(int i = 1; i <= 5; i ++)
    {
        cout << rand() << " ";
    }
    return 0;
}

運行n次結果

41 18467 6334 26500 19169
--------------------------------
Process exited after 0.576 seconds with return value 0
請按任意鍵繼續. . .

        如何產生更像“隨機數”的隨機數呢,這時候time(NULL)就排上用場。time(NULL)會返回自 Unix 紀元(January 1 1970 00:00:00 GMT)起的當前時間的秒數,因為時間在變,所以由rand()產生的隨機數就不固定了。
代碼如下:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
    srand(time(NULL));
    for(int i = 1; i <= 5; i ++)
    {
        cout << rand() << " ";
    }
    return 0;
}

運行第一次結果:

12114 22257 23578 61 16877
--------------------------------
Process exited after 0.5004 seconds with return value 0
請按任意鍵繼續. . .

運行第二次結果:

12212 17030 2447 1064 31402
--------------------------------
Process exited after 0.4893 seconds with return value 0
請按任意鍵繼續. . .
(可以看到,每次的結果不同)
三、隨機數的使用公式
       rand() % 隨機數的范圍的長度 + 隨機數范圍的最小值
       舉例:如果我要產生10 — 15 的隨機數,公式為 rand() % (15 - 10 + 1) + 10。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM