c - 获取退出值:-1,073,741,571 用简单的代码计算第 n 时刻
问题描述
我在计算随机数数组的第 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;
}
解决方案
在您的代码中,您在 size 堆栈上构造一个数组N
:int R[N]
我怀疑这会导致足够大的 N 值导致堆栈溢出。如果将行替换int R[N]
为int* R = malloc(sizeof(*R) * N);
使用 malloc 将堆分配您的R
数组而不是使用堆栈分配,这将避免可能的堆栈溢出
推荐阅读
- monaco-editor - 摩纳哥单线模式
- teamcity - teamcity 构建时出现纱线错误:“未知:未知错误,打开”
- javascript - 将预填充的数据与用户输入进行比较,并仅在已编辑的情况下提交表单
- javascript - Django在提交前检查复选框是否被选中
- javascript - addEventListener 和传递函数的问题
- android - 通过 ViewModelProvider 获取 ViewModel 实例
- spring-boot - 单元测试或模拟:在 Spring Boot 中使用 Rest 模板测试服务类
- blazor - Blazor:OnSubmit:如何访问表单输入值并显示 ValidationMessage?
- c - VST 型双关语
- assembly - arduino 组件发送和接收