簡體   English   中英

rand() 函數通過升序到前一個數字來生成下一個數字

[英]rand() function generates the next number by ascending to the previous number

請檢查下面給出的代碼。 它為每次執行生成的隨機數是上一次執行中生成的數字的增量。

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main()
{
    srand(time(NULL));

    cout<<"\n Random Number : "<<rand()<<endl;

    cin.get();
    return 1;
}

請執行 5-6 次,您會看到每次執行的隨機數都在增加,並且它們非常接近。

注意:請使用 CodeBlocks 或 Visual Studio 來檢查它,而不是在線編譯器。

實際上,我找到了解決問題的方法,但它仍然可能不是我問題的答案。 無論如何,問題不在於srand()rand()函數,而在於函數time(NULL) 由於我試圖在 Windows 上運行此代碼,而不是使用time(NULL)作為srand()的參數,我使用了GetTickCount() ,現在它為每次執行正確生成隨機數。

#include <iostream>
#include <cstdlib>
#include <windows.h>

using namespace std;

int main()
{
    srand(GetTickCount());

    cout<<"\n Random Number : "<<rand();

    cout<<"\n";
    cin.get();
    return 1;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM