0

I am working on a coin toss program. When I run this code, it returns 2, 100 times. Why is it not randomly returning 1's and 2's? (Thank you for helping me?

#include <iostream>
#include <string>


using namespace std;

int cointoss (){
    int toss=0;
    srand((int)time(NULL));

    //generating random number 1-2
    toss = rand() % 2 + 1;
    
    return(toss);
}
  
int main() {
    int toss = 0;

    for (int i=0; i<100; i++)
    {
        toss = cointoss();
        cout << toss << endl;
    }
    return 0;
    
}
Adrian Mole
  • 43,040
  • 110
  • 45
  • 72
  • You should not call `srand` in every iteration, but only once, see [this question](https://stackoverflow.com/questions/7343833/srand-why-call-it-only-once). Basically the "randomness" is reset everytime and the way RNG works means that the result won't change in the next call of `rand` – thinkgruen Nov 05 '21 at 11:26

0 Answers0