我正在构建一个简单的程序来计算骰子实验中数字的频率,但我尝试扩展它并将最大 throw 次数增加到巨大的数字,通过反复试验,我发现最大限制为519253。
使用这个最大值,我也无法创建任何新数组,它会崩溃。
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define MX 519253
#define DICE 6
void throwdice(int n[], int size);
int genNum();
void printv(int n[], int size);
void countd(int n[], int size, int count[DICE]);
int main ()
{
srand(time(NULL));
int throws[MX];
int count[DICE]={0};
int n;
//printf("Number of dice to throw: ");
//scanf("%d",&n);
n=MX;
throwdice(throws,n);
//printf("Throw\tNumber");
//printv(throws,n);
countd(throws,n,count);
printf("\n\nNumber\tFrequency");
printv(count,DICE);
}
int genNum()
{
int n;
n=rand()%DICE+1;
return n;
}
void printv(int n[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("\n%d \t%d",i+1,n[i]);
}
void throwdice(int n[], int size)
{
int i;
for (i = 0; i < size; i++)
n[i]=genNum();
}
void countd(int n[], int size, int count[DICE])
{
int i;
for (i = 0; i < size; i++)
count[n[i]-1]++;
}
有没有办法扩展这个程序来处理,比如一百万次抛出?
最佳答案
尝试改变这个;
int throws[MX];
为此,或者将其移至全局范围;
static int throws[MX];
我认为你可能溢出了堆栈。
你可以尝试像这样把数组放到堆上;
int *throws = malloc(sizeof(int)*MX);
关于c - 骰子实验,增加最大 throw 次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52193003/