【发布时间】:2016-05-26 17:10:34
【问题描述】:
我试图在 C 编程中用辛普森的方法做这个积分计算器,但它出现了一个错误:分段错误(核心转储)。我用谷歌搜索了一些关于它的东西并尝试了 gdb 调试器,但我什么也没得到。
gdb 声称: 程序收到信号 SIGSEGV,分段错误。 0x00000000004008f6 in main()
我不是专业的程序员,我不懂指针之类的东西。
这个错误是什么意思?我该如何解决?应该注意什么才能防止它发生/发现错误?
提前致谢(:
#include<stdio.h>
#include<math.h>
double inta,suma; //value of the integral and a provisory value for it
int a; //a sort of boolean
double expo(double x) //the function to be integrated
{
return exp(-0.5 * pow(x,2));
}
double integration(double min, double max, int division) //the process of integration
{
double step = (max - min)/(pow(2,division)); //define the number of steps
double fake_a;
fake_a = min; //a value thats equal to the minimum
int counter; // to count how many times the steps have been taken
counter = 1;
while(fake_a < max)
{
fake_a = fake_a + counter*step; //the first value of a
if(counter % 2 == 0) //even
{
suma = suma + 2*expo(fake_a);
counter++;
}
else //odd
{
suma = suma + 4*expo(fake_a);
counter++;
}
}
inta = suma + expo(min) + expo(max); //final value of the integral
counter = 1; //reset counter
return inta;
}
int main()
{
int N; //N of columns of matrix_inte
double matrix_inte[N][2]; //a matrix for the evaluating the integrals
a = 0; //boolean
double acc = pow(10,-6); //accuracy
N = 2; //length of the integral vector
int n_div; //number of divisions
double mn = -1.0;
double mx = 1.0;
n_div = 10;
//first values of the matrix
matrix_inte[1][1] = 0;
matrix_inte[2][1]= 1;
matrix_inte[1][2] = 0;
while(a=0) //main loop
{
for(int i=2;i<=N;i=i+1) //takes the differences of a vector[i] and vecotr[i-1]
{
double result;
result = fabs(matrix_inte[i][1]-matrix_inte[i-1][1]);
matrix_inte[i][2] = result;
}
for(int j = 1;j <= N; j = j + 1)
{
if(matrix_inte[j][2] > acc) //checks if there is any value greater than acc
{
n_div = n_div + 10;
N = N + 1;
inta = 0;
suma = 0; //readjusts the variables
integration(mn,mx,n_div);
matrix_inte[N][1] = inta; //recalculate the integral
}
else
{
printf("%f ", matrix_inte[j][1]); //shows the value of the integral
a = 1; //changes the boolean
}
}
}
return 0;
}
【问题讨论】:
-
你介意创建一个MCVE吗?
-
调试器会很容易地告诉您崩溃发生的准确位置。它可能是您访问包含 2 个元素的数组的第三个元素的地方,甚至在循环之前。
-
...并且
N在您使用double matrix_inte[N][2];时未初始化。 -
int N; double matrix_inte[N][2];:N未初始化。 -
while(a=0)->while(a == 0)
标签: c pointers ubuntu segmentation-fault