2010-08-06 27 views
2

我明白,使用srand(時間(0)),有助於設置隨機種子。但是,下面的代碼爲兩個不同的列表存儲相同的一組數字。如何在同一個程序/函數中每次生成不同的隨機數字集?

想知道,當以下函數被多次調用時,如何生成不同的數字集合。

void storeRandomNos(std::list<int>& dataToStore) 
{ 

    int noofElements = 0; 
    srand(time(0)); 


    noofElements = (rand() % 14) + 1; 

    while (noofElements --) 
    { 
     dataToStore.push_back(rand() % 20 + 1); 
    } 
} 

下面是其餘的代碼。

void printList(const std::list<int>& dataElements, const char* msg); 
void storeRandomNos(std::list<int>& dataToStore); 
int main() 
{ 
    std::list<int> numberColl1; 
    std::list<int> numberColl2; 


    storeRandomNos(numberColl1); 
    storeRandomNos(numberColl2); 

    printList(numberColl1 , "List1"); 
    printList(numberColl2 , "Second list"); 


} 


void printList(const std::list<int>& dataElements, const char* msg) 
{ 

    std::cout << msg << std::endl; 
    std::list<int>::const_iterator curLoc = dataElements.begin(); 

    for (; curLoc != dataElements.end() ; ++curLoc) 
    { 
     std::cout << *curLoc << ' '; 
    } 
} 

回答

2

在您的程序開始時執行一次srand(time(0))

+0

感謝您的解決方案。 – user373215 2010-08-06 12:42:25

6

當主程序啓動時,僅初始化一次RNG。不是每次你進入你的功能。否則,可能在同一秒內調用兩次函數,這可能會給你time(0)的相同結果。

+0

感謝您的解決方案。 – user373215 2010-08-06 12:41:42

8

一個僞隨機發生器,如rand(),只是一個數學函數,它接受一個輸入 - 種子 - 並對其進行一些處理。它返回它產生的新值,並將其設置爲新種子。下一次它將使用新的種子值。

因爲計算機是確定性的,所以每次用相同的種子調用rand()時,它會產生相同的輸出值。這就是爲什麼它是隨機。

在你的例子中,你使用了兩次相同的種子,因爲time(0)以秒爲單位返回時間,而你的兩個函數調用發生在同一秒內(因爲電腦速度很快)。

正如其他評論者所說,只需要一次種子到相當隨機的值(即當前時間)。

+0

感謝您的詳細解釋。 – user373215 2010-08-06 12:41:01

0

您需要使用srand(time(0))每個線程,在你的計劃,讓僞隨機號碼的呼叫rand()一次。

相關問題