C
celerysoup16
I've written this coin toss program, and can't figure out why it isn't
giving accurate results...
cheers,
Ben
#include <stdlib.h>
#include <stdio.h>
#define H 1
#define T 0
#define SENTINEL -1
int count=0, seed=3645, limit=200, in_a_row=6, iterations=100;
void one_run(int seed_passed)
{
int i, x, row_h;
row_h = 0;
seed=(1+seed_passed);
srand(seed);
char A[limit+1];
for(i=0;i<limit;i++)
{
x=(int)(2.0*rand()/(1.0+RAND_MAX));
if(x==H)
A=H;
else
A=T;
}
A=SENTINEL;
i=0;
while(A!=SENTINEL)
{
while(A==H)
{
i++;
row_h++;
}
if(row_h==in_a_row)
count++;
row_h=0;
if(A!=SENTINEL)
i++;
}
}
int main(int argc, char **argv)
{
int i;
double av_occur;
if (argc==2)
seed=atoi(argv[1]);
printf("\nEnter number of coin tosses: ");
scanf("%d", &limit);
printf("\nEnter number of heads to be found in a row: ");
scanf("%d", &in_a_row);
if(limit<=1000)
iterations=100000;
for(i=1;i<=iterations;i++)
{
one_run(seed);
}
(av_occur=1.0*count/iterations);
printf("\nIf a coin is flipped %d times:\n", limit);
printf("Average no. of occurances of %d heads in a row is %.5f"
, in_a_row, av_occur);
printf("\n(with %d tests)", iterations);
/* printf("\ncount is %d", count);
*/
return 0;
}
giving accurate results...
cheers,
Ben
#include <stdlib.h>
#include <stdio.h>
#define H 1
#define T 0
#define SENTINEL -1
int count=0, seed=3645, limit=200, in_a_row=6, iterations=100;
void one_run(int seed_passed)
{
int i, x, row_h;
row_h = 0;
seed=(1+seed_passed);
srand(seed);
char A[limit+1];
for(i=0;i<limit;i++)
{
x=(int)(2.0*rand()/(1.0+RAND_MAX));
if(x==H)
A=H;
else
A=T;
}
A=SENTINEL;
i=0;
while(A!=SENTINEL)
{
while(A==H)
{
i++;
row_h++;
}
if(row_h==in_a_row)
count++;
row_h=0;
if(A!=SENTINEL)
i++;
}
}
int main(int argc, char **argv)
{
int i;
double av_occur;
if (argc==2)
seed=atoi(argv[1]);
printf("\nEnter number of coin tosses: ");
scanf("%d", &limit);
printf("\nEnter number of heads to be found in a row: ");
scanf("%d", &in_a_row);
if(limit<=1000)
iterations=100000;
for(i=1;i<=iterations;i++)
{
one_run(seed);
}
(av_occur=1.0*count/iterations);
printf("\nIf a coin is flipped %d times:\n", limit);
printf("Average no. of occurances of %d heads in a row is %.5f"
, in_a_row, av_occur);
printf("\n(with %d tests)", iterations);
/* printf("\ncount is %d", count);
*/
return 0;
}