硬币抛掷模拟(使用数组)
如果抛掷硬币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");
}
}
作者:cpoint
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.