fprintf doesn't print when it undergoes a loop

戏子无情 提交于 2019-12-11 09:26:43

问题


I'm trying to print something in a document, but it only works for the first value of h that I tried! I was trying to figure it out myself, but I have to give this code to my professor in less than an hour, so I'm a bit desperate. :/

#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 is not relevant, so I didn't post it. It looks like it's something really stupid in the loop, because if I put h0 = 2.e-8 (which is the value I'm trying to print) it works for that value.


回答1:


I was able to fix it by making the file a parameter on the euler function and then calling it again after the loop, on a different file. That solved the problem, but I still don't understand why it wasn't working before.

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


来源:https://stackoverflow.com/questions/17305530/fprintf-doesnt-print-when-it-undergoes-a-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!