Nat*_*cha 1 c gcc pointers mingw
我必须制作一个程序,使用辛普森方法和梯形方法计算函数的积分.使用MinGW在我的计算机上工作得很好,但是当我尝试在我的uni计算机上编译它时,我得到:
It = 0 //should be 0.954499
*pn = 0 //should be 18
Is = 0 //should be 0.954500
*pn = 0 //should be 6
Run Code Online (Sandbox Code Playgroud)
这就是我提出的(对不起,变量和评论都是葡萄牙语,我会在回家后再修复):
integral.h:
#include <stdio.h>
#include <math.h>
#define eps 1.e-6
#define kmax 20
double trapezio(double (*f)(double x), double a, double b, int *n);
double simpson(double (*f)(double x), double a, double b, int *n);
Run Code Online (Sandbox Code Playgroud)
integral.c:
#include "integral.h"
#define xmin -2
#define xmax 2
double f(double x);
int main(){
double It,Is;
int n = 0;
int *pn = NULL;
pn = &n;
It = trapezio(f,xmin,xmax,pn)/sqrt(2*M_PI);
printf("Pelo metodo dos trapezios a integral vale aproximadamente %lf\n", It);
printf("O numero de iteracoes usadas foi %d\n\n",*pn);
*pn = 0;
Is = simpson(f,xmin,xmax,pn)/sqrt(2*M_PI);
printf("Pelo metodo de simpson a integral vale aproximadamente %lf\n", Is);
printf("O numero de iteracoes usadas foi %d\n",*pn);
return 0;
}
double f(double x){
return exp(-0.5*x*x); // Funcao que sera integrada
}
Run Code Online (Sandbox Code Playgroud)
trapezio.c:
#include "integral.h"
double trapezio(double (*f)(double x), double a, double b, int *n){
double To, Tk;
double soma;
int i, k = 1;
Tk = 0.5*(f(a) - f(b))*(b - a);
while (fabs((Tk-To)/To) > eps && k < kmax){
soma = 0; // Resetando variavel soma
To = Tk; // To e' T(k - 1), caso o loop se repita o ultimo Tk vira To
for (i = 1 ; i <= (pow(2,k)-1) ; i += 2) soma += f(a + i*(b - a)/pow(2.,k));
Tk = 0.5*To + soma*(b - a)/pow(2.,k);
k++;
*n += 1;
}
return Tk;
}
Run Code Online (Sandbox Code Playgroud)
simpson.c:
#include "integral.h"
double simpson(double (*f)(double x), double a, double b, int *n){
double So, Sk = 0;
double somaimp, somapar;
int i, k = 1;
while (fabs((Sk-So)/So) > eps && k < kmax){
somaimp = 0;
somapar = 0;
So = Sk; // So e' S(k - 1)
for (i = 1; i <= (pow(2,k)-1); i += 2) somaimp += f(a + i*(b - a)/pow(2.,k));
for (i = 2; i <= (pow(2,k)-2); i += 2) somapar += f(a + i*(b - a)/pow(2.,k));
Sk = (b - a)*(f(a) + 4*somaimp + 2*somapar + f(b))/(3*pow(2.,k));
k++;
*n += 1;
}
return Sk;
}
Run Code Online (Sandbox Code Playgroud)
编辑:我忘了提到如果我拿出指针,trapezio工作,但辛普森仍然返回0.
在trapezio(),To在while循环中使用它之前,你永远不会初始化:
double To, Tk;
/* ... no assignment to To ... */
while (fabs((Tk-To)/To) > eps && k < kmax){
Run Code Online (Sandbox Code Playgroud)
这意味着它将以未定义的方式运行,并且可能永远不会进入循环.