C/C++ 生成[X,Y]內的隨機數
在C語言中,rand()函式可以用來產生隨機數,但是這不是真真意義上的隨機數,是一個偽隨機數。是根據一個數,稱為種子,為基準以某個遞推公式推算出來的一系數,當這系列數很大的時候,就符合正態公佈,從而相當於產生了隨機數,但這不是真正的隨機數
rand()會返回一隨機數值,範圍在0至RAND_MAX 間。返回0至RAND_MAX之間的隨機數值,RAND_MAX定義在stdlib.h
在呼叫此函式rand()產生隨機數前,必須先利用srand()設好隨機數種子,如果未設隨機數種子,rand()在呼叫時會自動設隨機數種子為1,這樣每次呼叫生成的隨機數都是一致的。
如何每次產生不一致的隨機數:
srand((int)time(0));//用系統時間來做種子
rand()和srand()函式。這二個函式的工作過程如下:
1) 首先給srand()提供一個種子,它是一個unsigned int型別,其取值範圍從0~65535;
2) 然後呼叫rand(),它會根據提供給srand()的種子值返回一個隨機數(在0到32767之間)
3) 根據需要多次呼叫rand(),從而不間斷地得到新的隨機數;
例子:
-
#include<stdio.h>
-
#include<stdlib.h>
-
#include<time.h>
-
void main()
-
{
-
// srand((int)time(0));
-
int x;
-
int j;
-
for(x=0;x<10;x++)
-
printf("%d\t",rand_X(100));//輸出100內的隨機數
-
}
-
int rand_X(int x)
-
{
-
return rand()%x;
-
}
第1次執行結果:
41 67 34 0 69 24 78 58 62 64
第2次執行結果:
41 67 34 0 69 24 78 58 62 64
......
第n次執行結果:
41 67 34 0 69 24 78 58 62 64
每次執行產生不一樣的隨機數:使用系統時間作為種子
例子:
-
#include<stdio.h>
-
#include<stdlib.h>
-
#include<time.h>
-
void main()
-
{
-
srand((int)time(0));//使用系統時間作為隨機種子
-
int x;
-
int j;
-
for(x=0;x<10;x++)
-
printf("%d\t",rand_X(100));//輸出100內的隨機數
-
}
-
int rand_X(int x)
-
{
-
return rand()%x;
-
}
第1次執行:
84 9 54 43 84 24 48 39 71 54
第2次執行:
88 10 51 37 70 7 43 2 54 24
......
第n次執行:
32 87 43 47 59 43 18 74 67 53
如何產生設定範圍內的隨機數
-
要讓隨機數限定在一個範圍,可以採用模除加法的方式。
-
要產生隨機數r, 其範圍為 X<=r<=Y,可以使用如下公式:
-
rand()%(Y-X+1)+X
-
其原理為,對於任意數,
-
0<=rand()%(Y-X+1)<=Y-X
-
於是
-
0+X<=rand()%(Y-X+1)+X<=Y-X+X
-
即
-
X<=rand()%(Y-X+1)+X<=Y
程式碼驗證:
-
/**
-
生成[X,Y]的隨機數
-
//rand()%(Y-X+1)+X
-
*/
-
#include<stdio.h>
-
#include<stdlib.h>
-
#include<time.h>
-
void main()
-
{
-
// int flags[11];//標誌位
-
int i=0;
-
srand((int)time(0));//用系統時間作為隨機種子
-
int temp=-1;
-
int Y=10;
-
int X=0;
-
//驗證確實生成了[0,10]的隨機數
-
while(i<=10)
-
{
-
temp=rand()%(Y-X+1)+X;//生成[0,10]的隨機數
-
if(temp>10||temp<0)
-
{
-
printf("錯誤!\n");
-
break;
-
}
-
if(i==temp)
-
{
-
printf("temp=%d\n",temp);
-
i++;
-
}
-
}
-
}
結果:
-
temp=0
-
temp=1
-
temp=2
-
temp=3
-
temp=4
-
temp=5
-
temp=6
-
temp=7
-
temp=8
-
temp=9
-
temp=10
-
Process returned 8 (0x8) execution time : 0.250 s
-
Press any key to continue.
可以看到並沒有輸出錯誤:可見確實生成了[0,10]的隨機整數
C++實現:
這裡和C語言沒什麼區別,就是輸入輸出由printf,scanf,改成cout,cin而已。以及對應都標頭檔案上多加了一個c:#include<ctime>,#includ<cstdlib>
-
/**
-
C++中獲取隨機數[x,y]
-
*/
-
#include<iostream>
-
#include<ctime>
-
#include<cstdlib>
-
using namespace std;
-
int main()
-
{
-
srand((unsigned)time(NULL));
-
// srand((int)time(0));//這兩句結果都是一樣的
-
int Y=10;
-
int X=0;
-
int temps[11];
-
int i=0;
-
int temp;
-
while(i<=10)
-
{
-
temp=rand()%(Y-X+1)+X;
-
if(temp>10||temp<0)
-
{
-
cout<<"錯誤!"<<endl;
-
}
-
if(temp==i)
-
{
-
temps[i]=temp;
-
i++;
-
}
-
}
-
cout<<"i="<<i<<endl;
-
for(i=0;i<=10;i++)
-
{
-
cout<<temps[i]<<" ";
-
}
-
return 0;
-
}
結果:
-
i=11
-
0 1 2 3 4 5 6 7 8 9 10
-
Process returned 0 (0x0) execution time : 0.664 s
-
Press any key to continue.