我在用这段代码计算随机数组的第n次力矩(比如质心,应该是第1次力矩)时遇到了问题。 我在eclipse中用C语言编码,当我尝试用gcc编译时也会出现这个错误。 当我运行N<1000000的代码时,代码运行正常。 但是当我尝试输入一个更高的N值,比如1000000或者100万,代码给我的退出值是-1,073,741,571,并且没有像应该的那样打印出时刻。 我想这和内存有关。
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
//here we import the three libraries
//we start our main function
int main ()
{
setbuf(stdout, NULL);
//setbuf disables buffering so print statements print properly
int i,N;
unsigned int seed;
double first,second,third,fourth,fifth,sixth,firsttot,secondtot,thirdtot,fourthtot,fifthtot,sixthtot;
//here we declare the vars to be used
printf("\nEnter number of iterations and seed");
printf("\n");
scanf("%i %u", &N, &seed);
srand(seed);
//asks user for input, scans the input, and takes the seed to set a starting point for the rand() function called in the for loop
//since my R array depends on the user, i declare the array here, after the user inputs the size of the array
double R[N];
for (i=0;i<N;i=i+1)
{
R[i]=(double)rand()/RAND_MAX;
//printf("%12.8lf \n",R[i]);
}
//the for loop sets R equal to a random value using our seed with (double)rand()
printf("\n");
//here, we have for loops to add up the individual nth moments for each point of the array
firsttot = 0.0;
for (i=0;i<N;i=i+1)
{
firsttot = firsttot + pow(R[i],1);
}
secondtot = 0.0;
for (i=0;i<N;i=i+1)
{
secondtot = secondtot + pow(R[i],2);
}
thirdtot = 0.0;
for (i=0;i<N;i=i+1)
{
thirdtot= thirdtot + pow(R[i],3);
}
fourthtot = 0.0;
for (i=0;i<N;i=i+1)
{
fourthtot = fourthtot + pow(R[i],4);
}
fifthtot = 0.0;
for (i=0;i<N;i=i+1)
{
fifthtot = fifthtot + pow(R[i],5);
}
sixthtot = 0.0;
for (i=0;i<N;i=i+1)
{
sixthtot = sixthtot + pow(R[i],6);
}
//now, we take the actual nth moment by dividing each total by N;
first = firsttot/N;
second = secondtot/N;
third = thirdtot/N;
fourth = fourthtot/N;
fifth = fifthtot/N;
sixth = sixthtot/N;
printf("\nThe first moment is: %lf",first);
printf("\nThe second moment is: %lf",second);
printf("\nThe third moment is: %lf",third);
printf("\nThe fourth moment is: %lf",fourth);
printf("\nThe fifth moment is: %lf",fifth);
printf("\nThe sixth moment is: %lf",sixth);
return 0;
}
在你的代码中,你在堆栈上构造了一个大小为1的数组。N
: int R[N]
我怀疑这是在N值足够大的情况下造成堆栈溢出的原因。int R[N]
与 int* R = malloc(sizeof(*R) * N);
使用malloc会对你的 R
数组,而不是使用堆栈分配,这将避免可能的堆栈溢出。