my rand() works only if i use a cout

Hi,
i'm doing a function to "flip a coin" and every time i try to start the program it works fine only if the code has a casual cout.
I'm using visual studio.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
  #include <iostream>
using std::cout;
using std::cin;
using std::endl;

#include <cstdlib>
using std::rand;
using std::srand;

#include <ctime>
using std::time;

int flip();

int main()
{
    int testa = 0;//0
    int croce = 0;//1
    for (int i = 0; i < 100000; i++)
    {
        if (flip()== 0)
            testa++;
        else
            croce++;
    }
    cout << "Testa: " << testa << endl << "Croce: " << croce << endl;
    return 0;
}

int flip()
{
    int porcodio;
    srand(time(0));
    porcodio = rand() % 2;
    //cout << "porcodio" << endl; //here if i use this cout the function 
                                  //works 
    return porcodio;
}


my output without cout:
Testa: 100000
Croce: 0

my output with cout:
porcodio
porcodio
porcodio
...
Testa: 58010
Croce: 41990
Printing just slows down your program enough such that it takes multiple seconds to complete, giving different srand seeds.

Move the srand call to be BEFORE your for loop.

PS: Cool it with the blasphemous remarks!
Last edited on
Thanks now it works I hadn't really considered the time(0);
Topic archived. No new replies allowed.