2013-06-19 53 views
1

我必須製作一個程序,使用辛普森方法和梯形方法計算函數的積分。它的工作原理使用MinGW的我的電腦上就好了,但是當我嘗試編譯它在我的單向的電腦,我得到:代碼適用於MinGW,但不適用於我的uni計算機(語言C)

It = 0 //should be 0.954499 
*pn = 0 //should be 18 
Is = 0 //should be 0.954500 
*pn = 0 //should be 6 

這是我想出了(對不起變量和意見是在葡萄牙,我LL修復後後我回家):

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); 

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 
} 

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; 
} 

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; 
} 

編輯:我忘了提,如果我帶指針出來,trapezio工作,但仍辛普森返回0

+0

你的uni計算機上的操作系統和編譯器是什麼? – nouney

回答

6

trapezio(),你從來沒有在while循環使用前初始化To

double To, Tk; 
/* ... no assignment to To ... */ 
while (fabs((Tk-To)/To) > eps && k < kmax){ 

這意味着它將以不確定的方式運行,並且可能永遠不會進入循環。

+0

我認爲,因爲我定義了循環開始後沒有問題,但我忘了循環條件依賴於。謝謝。 :) –

+0

最近MSVC編譯器會默認警告(至少從VS 2005開始)。有趣的是,即使使用'-Winitialized -Wmaybe-uninitialized',我也無法讓gcc警告這個特殊情況。 –

+0

爲什麼我的代碼在MinGW上工作?它認爲我的while循環是do/while循環嗎?這很奇怪。 –

相關問題