dimanche 16 juin 2019

Random number like java in c++

I have a need to generate a random number 0 or 1 to simulate the coin toss. It is easily possible in Java whereas in C++ I am having difficulty. I searched in a lot but didn't find a satisfactory answer. There are many random related questions in stackoverflow, but none of them answer this. If you can help, it will be really appreciable.

Here is my code

for (size_t i = 0; i < 50; i++)
    {
        srand(time(0));
        int k = rand() % 2;
        cout << k;
    }

The output is all 0 or 1. It is because the seed for srand is same time.

Is there any solution for this?




Aucun commentaire:

Enregistrer un commentaire