rand() returns the same number each time the program is run

后端 未结 6 1763
自闭症患者
自闭症患者 2021-02-02 10:46

In this rather basic C++ code snippet involving random number generation:

include 
using namespace std;

int main() {
    cout << (rand() %         


        
6条回答
  •  萌比男神i
    2021-02-02 11:26

    You are not seeding the number.

    Use This:

    #include 
    #include 
    
    using namespace std;
    
    int main()
    {
        srand(static_cast(time(0)));
        cout << (rand() % 100) << endl;
        return 0;
    }
    

    You only need to seed it once though. Basically don't seed it every random number.

提交回复
热议问题