这是一个使用数值求积法计算定积分的程序(我不知道这是否是正确的翻译):
#include <math.h>
#include <stdio.h>
float f(float x){
float y;
y = 4/(+x*x);
return y;
}
void quadra(float a, float b, float *Q, float *E, float f(float)){
float q1, q2, m, h, fa, fb;
h = b - a;
fa = f(a);
fb = f(b);
q1 = (fa+fb)*h/2.;
m = (a+b)/2.;
q2 = ( (fa+2*f(m)+fb) ) *h/4;
*Q = q2;
*E = fabs(q2-q1)/3;
}
void scambia(float *x, float *y) {
float z;
z = *x;
*x = *y;
*y = z;
return;
}
void sort(float x[], int n) {
int flag=1, k=n-1, i;
while (flag == 1 && k > 0) {
flag = 0;
for (i=0; i<k; i++) {
if (x[i]>x[i+1]) {
scambia(&x[i], &x[i+1]);
flag = 1;
}
}
k = k-1;
}
return;
}
int intautri(float A, float B, float TOL, int MAXFUN, float *Q, float *E, int *N, float FUN(float)){
void sort(float [], int);
void quadra(float, float, float*, float*, float(float));
float Q1,Q2,c,d,Iold,Eold,E0,E1,E2,alist[100],blist[100],qlist[100],elist[100];
int n, flag;
quadra(A, B, &Q1, &E0,FUN);
*N = 3;
n = 1;
alist[n] = A;
blist[n] = B;
qlist[n] = Q1;
elist[n] = E0;
*Q = Q1;
*E = E0;
if (*E<=TOL || *N>=MAXFUN){
flag = 1;
}else{
c = alist[n];
d = blist[n];
Iold = qlist[n];
Eold = elist[n];
n = n-1;
quadra(c, (c+d)/2, &Q1, &E1, FUN);
quadra((c+d)/2, d, &Q2, &E2, FUN);
*Q = *Q - Iold + Q1 + Q2;
*E = *E - Eold + E1 + E2;
*N = *N + 6;
intautri(A , B, TOL, MAXFUN, Q, E, N, FUN);
alist[n+1] = c;
blist[n+1] = (c+d)/2;
qlist[n+1] = Q1;
elist[n+1] = E1;
alist[n+2] = (c+d)/2;
blist[n+2] = d;
qlist[n+2] = Q2;
elist[n+2] = E2;
n = n+2;
sort(alist, n);
sort(blist, n);
sort(qlist, n);
sort(elist, n);
flag = 0;
}
;
return flag;
}
int main(){
int intautri(float, float, float, int, float *, float *, int*, float(float));
float TOL, MAXFUN, A, B,Q,E;
int N, J;
float f(float);
A = 0;
B = 1;
TOL = 0.0001;
MAXFUN = 200;
J = intautri(A, B, TOL, MAXFUN, &Q, &E, &N, f);
printf("%d\n", J);
printf("%d\n", N);
printf("%f\n", Q);
return 0;
}
无论如何我编译没有代码问题,但是当我运行它时#34;分段错误(核心转储)&#34;出现在终端上。我知道错误可能取决于内存分配,但我不明白出了什么问题......你能帮助我吗?
答案 0 :(得分:1)
intautri
中有退出条件:
if (*E<=TOL || *N>=MAXFUN){
但在功能的开头你也有:
*N = 3;
这意味着您的第二个退出条件永远不会触发。在不试图理解代码逻辑的情况下,我相信你应该:
N
初始化main()
。*N = 3
。intautri()
作业