利用srand和rand生成隨機數

2021-10-19 12:09:00 字數 524 閱讀 3253

rand函式用於生成初始值a和區間長度d組成區間[a,a+d]之間的隨機數,rand使用之前必須利用srand函式設定種子,否則多次執行結果相同。

使用:1.(rand()%d)+a; 2.rand()%d+a;

srand函式是初始化隨機數發生器,用於設定rand()產生隨機數時的種子。傳入的引數seed為unsigned int型別,通常我們會使用time(0)或time(null)的返回值作為seed。

使用:srand((unsigned) int seed);

其中int seed通常為time(null)或time(0),time()的返回值是乙個很大的數,用於生產隨機數種子。

例.(生成1~100的隨機數)

#include

#include

#include

int main()

VS2010中srand和rand產生隨機數的用法

1.vc和vs2010中srand 和rand 函式的區別 在vc中rand 和srand 函式是包含在math.h標頭檔案中,在使用時需要新增 include math.h 或者 include 但是在vs2010中srand 和rand 是包含在stdlib.h中的,在使用時需要新增語句 inc...

srand 和rand 函式詳解

c語言 c 或 int rand void void srand unsigned seed 函式說明 rand函式產生的隨機數嚴格意義講不是真正的隨機數,它裡面採用了線性同餘法計算出隨機數,該方法有個最大週期m,也就是說該方法實在一定的範圍內生成一串數字,不過這個m一般來說比較大,所以正常使用時一...

C 利用srand和rand產生隨機數

他人部落格,時間久了,忘記 轉的了。以後發現再補充出處。產生一到十的十個隨機數 include include include include using namespace std define max 10 int main int main srand unsigned time null f...