我正在尝试使用Simpson的C编程方法中的这个积分计算器,但它出现了一个错误:分段错误(核心转储)。我搜索了一些有关它的东西并尝试了gdb调试器,但我什么也没得到。
gdb声称: 程序接收信号SIGSEGV,分段故障。 main()
中的0x00000000004008f6我不是专家程序员,我不了解指针和这类东西。
这个错误是什么意思?我该如何解决?应该注意什么,以防止它发生/发现错误?
提前致谢(:
#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;
}
答案 0 :(得分:2)
如何读取编译器消息?
while(a = 0){ … }
是一个对你的循环没有影响的语句,因为它将a
赋值为0
,这对你的循环没有条件检查。您应该使用等式比较运算符while(a == 0){ … }
接下来,2
已超过数组double matrix_inte[N][2]
的结尾。
matrix_inte[1][2] = 0;
所以在这里,但N
永远不会被初始化。
matrix_inte[i][2] = result;
希望这可以提供帮助。