rand()函數
- 作用: rand()函數是產生隨機數的一個隨機函數。
- 頭文件:#include < stdlib.h > (c) #include < cstdlib >(c++)
- rand()函數是按指定的順序來產生0~RAND_MAX之間的一個隨機整數,因此每次執行上面的語句都打印相同的兩個值,所以說C語言的隨機並不是真正意義上的隨機,有時候也叫僞隨機數。
srand()函數-初始化隨機數發生器
- 作用:可以指定不同的數(無符號整數變元)爲rand()函數的種子,我們通常使用time(NULL)函數返回的時間作爲種子;
實例
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
const int MAX = 100;
int main(int argc, char const *argv[])
{
srand(time(NULL));
for(int i = 0; i < 10; ++ i)
{
int temp = rand() % MAX;
cout << temp << endl;
}
return 0;
}