fprintf在经历循环时不会打印

时间:2013-06-25 19:08:06

标签: c do-while printf

我正在尝试在文档中打印某些内容,但它只适用于我尝试的第一个h值!我试图弄明白自己,但我必须在不到一个小时的时间内将这些代码交给我的教授,所以我有点绝望。 :/

#include <stdio.h>
#include <math.h>

double euler(double v0, double *t0, double h, double (*f)(double));
double dv(double v);

int main(){
    double vlim, t = 0;
    double *pt = &t;
    double h0 = 1.e-7;

    vlim = euler(0, pt, h0, dv);
    printf("O tempo e a velocidade limite para um passo de %.0e s sao respectivamente:\n", h0);
    printf("%.0e s e %lf mm/s.\n\n", *pt, vlim);

    double h = h0, v = 0;
    do {
        *pt = 0;
        v = euler(0, pt, h, dv);
        h /= 5.;
    } while (fabs(v-vlim)/v > 1e-5);

    printf("O passo necessario para atingir a convergencia na velocidade limite e' %.1e s.\n",h);
    return 0;
}

double euler(double y, double *x, double h, double (*f)(double)){
    FILE *arq = fopen("bolha.dat","w+");
    double y0, eps = 1e-4;
    do{
        y0 = y;
        y = y0 + h*f(y0); // Metodo de Euler
        *x += h;
        fprintf(arq, "%.1e\t%.7lf\n", *x, y);
    } while (fabs((y-y0)/y) > eps);

    fclose(arq);
    return y;
}

dv不相关,所以我没有发布。看起来它在循环中是非常愚蠢的,因为如果我把h0 = 2.e-8(这是我试图打印的值)它适用于该值。

1 个答案:

答案 0 :(得分:0)

我能够通过使文件成为euler函数的参数然后在循环之后再次在另一个文件上调用它来修复它。这解决了这个问题,但我仍然不明白为什么它之前没有工作。

#include <stdio.h>
#include <math.h>

double euler(double v0, double *t0, double h, double (*f)(double), FILE *arquivo);
double dv(double v);

int main(){
    FILE *saida = fopen("bolhateste.dat","w+");
    double vlim, t = 0;
    double *pt = &t;
    double h0 = 1.e-7;

    vlim = euler(0, pt, h0, dv, saida);
    printf("O tempo e a velocidade limite para um passo de %.0e s sao respectivamente:\n", h0);
    printf("%.0e s e %lf mm/s.\n\n", *pt, vlim);

    double h = h0, v = 0;
    do {
        *pt = 0;
        v = euler(0, pt, h, dv, saida);
        h /= 5.;
    } while (fabs(v-vlim)/v > 1e-5);

    saida = fopen("bolha.dat","w+");
    euler(0, pt, h, dv, saida);

    printf("O passo necessario para atingir a convergencia na velocidade limite e' %.1e s.\n",h);
    return 0;
}

double euler(double y, double *x, double h, double (*f)(double), FILE *arquivo){
    double y0, eps = 1e-4;
    do{
        y0 = y;
        y = y0 + h*f(y0); // Metodo de Euler
        *x += h;
        fprintf(arquivo, "%.1e\t%.7lf\n", *x, y);
    } while (fabs((y-y0)/y) > eps);

    return y;
}