C 中如何在乙個範圍內產生隨機數

2021-10-01 08:40:59 字數 445 閱讀 5300

要取得[a,b)的隨機整數,使用(rand() % (b-a))+ a;

要取得[a,b]的隨機整數,使用(rand() % (b-a+1))+ a;

要取得(a,b]的隨機整數,使用(rand() % (b-a))+ a + 1;

通用公式:a + rand() % n;其中的a是起始值,n是整數的範圍。

要取得a到b之間的隨機整數,另一種表示:a + (int)b * rand() / (rand_max + 1)。

要取得0~1之間的浮點數,可以使用rand() / double(rand_max)。

使用rand() % (int)n,產生[0, n)之間的偽隨機數:

#include #include #include using namespace std;

int main()

c c vc產生任意範圍內的隨機數

大家都知道c語言中的隨機函式random,可是random函式並不是ansi c標準,所以說,random函式不能在gcc,vc等編譯器下編 譯通過。那麼怎麼實現vc語言中的隨機函式呢?其實,除了random函式,還有乙個rand函式,這個函式也是乙個隨機函式,他可以產生從0到rand max 32...

C 中產生一定範圍內的隨機數

如果讓你用c 來生成0 n 1之間的隨機數,你會怎麼做?你可能會說,很簡單,看 srand unsigned time null rand n 仔細想一下,這個結果是隨機的嗎 當然,我們不考慮rand 函式的偽隨機性 不是的,因為rand 的上限是rand max,而一般情況下,rand max並不...

C 隨機生成區間範圍內的隨機數

要取得 a,b 的隨機整數,使用 rand b a a 要取得 a,b 的隨機整數,使用 rand b a 1 a 要取得 a,b 的隨機整數,使用 rand b a a 1 通用公式 a rand n 其中的a是起始值,n是整數的範圍。要取得a到b之間的隨機整數,另一種表示 a int b ran...