c++如何生成隨機數
阿新 • • 發佈:2018-11-27
使用rand()函式
標頭檔案<stdlib.h>
(1) 如果你只要產生隨機數而不需要設定範圍的話,你只要用rand()就可以了:rand()會返回一隨機數值, 範圍在0至RAND_MAX 間。RAND_MAX定義在stdlib.h, 其值為2147483647。
例如:
#include<stdio.h>
#include<stdlib.h>
void main()
{
for(int i=0;i<10;i+)
printf("%d/n",rand());
}
(2) 如果你要隨機生成一個在一定範圍的數,你可以在巨集定義中定義一個random(int number)函式,然後在main()裡面直接呼叫random()函式
x = rand()%11; /*產生1~10之間的隨機整數*/
y = rand()%51 - 25; /*產生-25 ~ 25之間的隨機整數*/
z = ((double)rand()/RAND_MAX)*(b-a) + a;/*產生區間[a,b]上的隨機數*/
例如:
#include<iostream> #include<stdlib.h> using namespace std; #define random(x) (rand()%x) void main() { for (int i = 0; i < 10; i++) { cout << random(10) << " "; } cout << endl; system("pause"); }
(3)但是上面兩個例子所生成的隨機數都只能是一次性的,如果你第二次執行的時候輸出結果仍和第一次一樣。這與srand()函式有關。srand()用來設定rand()產生隨機數時的隨機數種子。在呼叫rand()函式產生隨機數前,必須先利用srand()設好隨機數種子(seed), 如果未設隨機數種子, rand()在呼叫時會自動設隨機數種子為1。上面的兩個例子就是因為沒有設定隨機數種子,每次隨機數種子都自動設成相同值1 ,進而導致rand()所產生的隨機數值都一樣。
srand()函式定義 :
void srand (unsigned int seed);
通常可以利用geypid()或time(0)的返回值來當做seed,如果你用time(0)的話,要加入標頭檔案 #include<time.h>
例如:
#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
#define random(x) (rand()%x)
void main() {
srand((int)time(0));
for (int i = 0; i < 10; i++) {
cout << random(10) << " ";
}
cout << endl;
system("pause");
}
(4)隨機產生(a,b)區間內的隨機數
#include<iostream>
#include<stdlib.h>
#include<time.h>
#include<iomanip>
using namespace std;
#define random(a,b) (((double)rand()/RAND_MAX)*(b-a)+a)
void main() {
srand((int)time(0));
for (int i = 0; i < 100; i++) {
cout << random(0, 10) << " ";
}
cout << endl;
system("pause");
}
(5)四捨五入,返回整數,通過floor和ceil函式實現
#include<iostream>
#include<stdlib.h>
#include<time.h>
#include<iomanip>
using namespace std;
/*四捨五入,返回整數*/
double round(double r)
{
return (r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5);
}
double randomRange(double a, double b)
{
double x = (double)rand() / RAND_MAX;
double result = x*(b - a) + a;
return round(result);
}
void main() {
srand((int)time(0));
for (int i = 0; i < 100; i++) {
//cout << fixed << setprecision(0) << randomRange(0, 10) << " ";
cout << randomRange(0, 10) << " ";
}
cout << endl;
system("pause");
}