C++產生隨機數
// rand(), srand(), time()
// 編譯之後,每次運行產生的隨機數是一樣的
#include <iostream>
#include <cstdlib> // rand()和srand()頭文件是cstdlib
using namespace std;
int main(int argc, char* argv[])
{
for (int i = 0; i < 10; i++)
{
cout << rand()%100 << " ";
}
cout << endl;
return 0;
}
// 這樣編譯之後,每次運行產生的隨機數是不變的。可以試試。
// 若要產生真正的隨機數,需要配合srand()和time()
// rand()產生的隨機數是基於種子計算產生的。每次編譯,編譯器初始化一個種子,之後產生的隨機數都是基於同一個種子計算得到的,所以每次運行產生的隨機數是一樣的。
// srand(int)的作用是根據參數產生一個種子,參數不同,產生的種子不同。time(0)得到系統時間。srand(int(time(0)))便是根據系統時間產生種子。
#include <iostream>
#include <cstdlib> // rand()和srand()
#include <ctime> // time()
using namespace std;
int main(int argc, char* argv[])
{
srand(int(time(0)));
for (int i = 0; i < 10; i++)
{
cout << rand()%100 << " ";
}
cout << endl;
return 0;
}