problem with rand()

So, this is my coding below. Both T and H are 2 dollar and it should end when it gets H. Runs 10 games.

#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;

int main()
{
srand(time(0));
int i;
bool out = true;
double money = 0, total = 0, average;

for (i = 1; i <= 10; i++)
{
do
{
int coinflip = rand() % 2;
if (coinflip == 1)
{
cout << "H" << endl;
total = 2.00;
out = false;
}
if (coinflip == 0)
{
cout << "T";
money = 2.00;
total *= money;
}

} while (out);
cout << "You win $ " << total << endl;
}
average = total / 10;
cout << "The average payout was $" << average << endl;

return 0;
}
displys
H
You win $ 2
TYou win $ 4
H
You win $ 2
TYou win $ 4
TYou win $ 8
H
You win $ 2
H
You win $ 2
TYou win $ 4
TYou win $ 8
TYou win $ 16
The average payout was $1.6


And this is what it was suppose to display

TTTH You win $16.00
TH You win $4.00
TH You win $4.00
H You win $2.00
TTTTH You win $32.00
TH You win $4.00
H You win $2.00
H You win $2.00
TH You win $4.00
TH You win $4.00
The average payout was $7.40

You already have a post on the frontpage with identical title and same code on the top of the frontpage, you dont have to create a new one.

Could you please put your code between code tags
<> http://www.cplusplus.com/articles/jEywvCM9/

And your output in output tags
After first win out remain always false.
The code can be simpler (simpler code is less likely to contain errors):
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
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>

int main()
{
    std::srand( std::time(0) ) ;
    const int N = 10 ;

    double total = 0 ;

    for( int i = 0 ; i < N ; ++i )
    {
        int amount_won = 2 ; // amount won is at least two (for the terminating H)

        while( std::rand() % 1000 < 500  ) // half the time, till a head comes up
        {
            amount_won += 2 ; // add $2 for every T
            std::cout << 'T' ;
        }

        std::cout << "H You win $" << amount_won << ".00\n" ;

        total += amount_won ;
    }

    std::cout << "\naverage: $" << std::fixed << std::setprecision(2) << total / N << '\n' ;

}

http://coliru.stacked-crooked.com/a/6b19754615c15957
Last edited on
Topic archived. No new replies allowed.