c语言各类随机函数,怎样让c语言中的随机函数真正随机?
該樓層疑似違規已被系統折疊?隱藏此樓查看此樓
在C語言函數庫中包含了一個產生隨機數的函數:
int?rand(?void?);
在函數庫中對這個函數的說明是:
The?rand?function?returns?a?pseudorandom?integer?in?the?range
0?to?RAND_MAX.?Use?the?srand?function?to?seed?the?pseudorandom
-number?generator?before?calling?rand.
而在C語言函數庫中是這樣定義RAND_MAX的:
/*?Maximum?value?returned?by?"rand"?function
*/
#define?RAND_MAX?0x7FFF
所以,函數int?rand(?void?);返回的是一個界于0~32767(0x7FFF)之
間的偽隨機數,包括0和32767。注意,這里產生的是偽隨機數,不是真正意
義上的隨機數,看下面的程序:
#include?"stdlib.h"
#include?"stdio.h"
void?main(?void?)
{
/*?Display?a?number.?*/
printf(?"?%6d\n",?rand()?);
getchar();
}
程序運行的結果是:
346
多次運行這個程序,發現每次產生的結果都是346(不同的機器可能產生
的結果不一樣),這就是所謂的偽隨機數。偽隨機數是通過一個公式來運算
出來的,所以,每次產生的偽隨機數都一樣。那么,如何才能產生真正意義
上的隨機數呢?這就有一個隨機種子的問題。在C語言標準函數庫中,有這
么一個函數:
void?srand(?unsigned?int?seed?);
在《The?c?programming?language》中對這個函數是這樣描述的:
srand?uses?seed(函數變量聲明中的seed)?as?the?seed(隨機函數中種子
的意思)?for?a?new?sequence?of?pseudo-random?numbers.?The
initial?seed?is?1.
所以,要產生真正意義上的隨機數,那么就要求每次提供的種子不一樣,一
般情況下,都設置時間為隨機函數的種子。看下面的一段程序:
/*?RAND.C:?This?program?seeds?the?random-number?generator
*?with?the?time,?then?displays?10?random?integers.
*/
#include?"stdlib.h"
#include?"stdio.h"
#include?"time.h"
void?main(?void?)
{
int?i;
/*?Seed?the?random-number?generator?with?current?time?so?that
the?numbers?will?be?different?every?time?we?run.
將當前時間設置成隨機函數的種子,所以每次產生的數都不一樣
*/
srand(?(unsigned)time(?NULL?)?);
/*?Display?10?numbers.?*/
for(?i?=?0;?i?
printf(?“?%6d\n”,?rand()?);
}
Output
6929
8026
21987
30734
20587
6699
22034
25051
7988
10104
每次運行這個程序,產生的隨機數都不一樣,這樣就達到了隨機數的要求了
。
注意,rand這個函數產生的隨機數的范圍是0~32767,如果要產生100以內
的隨機數怎么辦呢?在標準C語言庫中并沒有定義產生給定范圍的隨機數的
函數。其實,要產生給定范圍的隨機數,只要做一個取余(%)運算就可以了
。下面是一個產生10以內隨機數的函數:
#include?"stdlib.h"
#include?"stdio.h"
#include?"time.h"
int?rand2(?void?);
void?main(?void?)
{
int?i;
/*?Seed?the?random-number?generator?with?current?time?so?that
·?the?numbers?will?be?different?every?time?we?run.
*/
srand(?(unsigned)time(?NULL?)?);
/*?Display?10?numbers:0~9?*/
for(?i?=?0;?i?
printf(?"?%6d\n",?rand2()?);
getchar();
}
int?rand2(?void?)
{
return?rand()?%?10?;
}
運行結果:
2
5
7
9
0
1
3
5
8
3
在這個程序中,我自己寫了一個函數rand2(),來產生10以內的隨機數,其
實,打開標準庫中的頭文件?Stdlib.h?就會發現有這樣的一條語句:
#define?random(num)?(rand()?%?(num))
上面的這行代碼是為了方便產生給定范圍的隨機數的,思路也是采用取余的
方法,所以上面的程序也可以改成:
#include?"stdlib.h"
#include?"stdio.h"
總結
以上是生活随笔為你收集整理的c语言各类随机函数,怎样让c语言中的随机函数真正随机?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 杭电c语言课程设计实验7,杭电1072
- 下一篇: html表单的常用属性有哪些,html/