如果抛掷硬币N次,看到头像的期望值是N/2次,但实际值也可能是0~N次,以下程序进行M次试验,M和N都从命令行获取。它使用一个数组f来跟踪出现“i次头像”的概率,其中0<=i<=N。然后打印试验结果的柱状图。
#include <stdlib.h>
#include
<
stdio.h
>
int heads()
{ return rand() < RAND_MAX / 2 ; }
main( int argc, char * argv[])
{ int i, j, cnt;
int N = atoi(argv[ 1 ]), M = atoi(argv[ 2 ]);
int * f = malloc((N + 1 ) * sizeof ( int ));
for (j = 0 ; j <= N; j ++ ) f[j] = 0 ;
for (i = 0 ; i < M; i ++ , f[cnt] ++ )
for (cnt = 0 , j = 0 ; j <= N; j ++ )
if (heads()) cnt ++ ;
for (j = 0 ; j <= N; j ++ )
{
printf( " %2d " , j);
for (i = 0 ; i < f[j]; i += 10 ) printf( " * " );
printf( " \n " );
}
}
int heads()
{ return rand() < RAND_MAX / 2 ; }
main( int argc, char * argv[])
{ int i, j, cnt;
int N = atoi(argv[ 1 ]), M = atoi(argv[ 2 ]);
int * f = malloc((N + 1 ) * sizeof ( int ));
for (j = 0 ; j <= N; j ++ ) f[j] = 0 ;
for (i = 0 ; i < M; i ++ , f[cnt] ++ )
for (cnt = 0 , j = 0 ; j <= N; j ++ )
if (heads()) cnt ++ ;
for (j = 0 ; j <= N; j ++ )
{
printf( " %2d " , j);
for (i = 0 ; i < f[j]; i += 10 ) printf( " * " );
printf( " \n " );
}
}