#include <iostream>
#include <string>
#include<ctime>
#include<cstdlib>
using namespace std;
int MaxNum(const int xValue, const int *yValue) //有可能後面的int*指針是一個數組的首元素指針
{
return xValue > *yValue ? xValue : *yValue;
}
int main()
{
srand((unsigned)time(NULL)); //生成隨機數種子
int a[10];
for (auto &i : a)
i = rand() % 10;
int b;
cin >> b;
cout << "較大值爲: ";
cout << MaxNum(b, a)<<endl;
cout << "數組全部元素爲: ";
for (auto j : a)
cout << j << ' ';
system("pause");
return 0;
}
主要來看看srand() rand() time()函數
首先要明白的是:計算機並不能產生真正的隨機數,而是已經編寫好的一些無規則排列的數字存儲在電腦裏,把這些數字劃分爲若干相等的N份,併爲每份加上一個編號用srand()函數獲取這個編號,然後rand()就按順序獲取這些數字,當srand()的參數值固定的時候,rand()獲得的數也是固定的。
那麼srand()產生的編號在這裏我們稱爲種子,一旦種子固定,產生的隨機數序列也是固定了的。所以我們在使用rand()前,可以用srand()產生種子,如果直接調用rand(),默認是srand(1)。 而此程序中我們用srand((unsigned)time(NULL)) 來產生種子。也就是time()這個函數,time(NULL)返回當前的系統時間,我們再用強制轉換爲unsigned,這樣就可以每次調用這個srand()時,產生的種子都不一定。這樣僞隨機數的隨機性更大。
詳細的產生隨機數函數可以看看這個:http://blog.csdn.net/jx232515/article/details/51510336