c - 我需要我的方程式在循环的每 10 次迭代中覆盖文件中的数据

标签 c loops for-loop

double rho[1001], rhonew[1001];

int main(void)
{
    int tstep, tmax, n, nmax, r;
    double t, dt, x, dx;
    dt = 0.001;
    tmax = 1000;
    dx = 0.1;
    nmax = 1000;
    rho0=1.0;
    r=1;

    FILE *afinal;
    afinal = fopen("afinal.txt","w");
    FILE *amid;
    amid = fopen("amid.txt","w");

    for (n = 0; n <= nmax; n++)
    {
        rho[n] = 500;
    }        

    for (n = 0; n <= nmax; n++)
    {
        rhonew[n] = 1;
    }
    for (tstep=1; tstep<=tmax; tstep++)
    {
        rho[tstep] += -tstep;
        if(tstep == r*10)
//I want this if statement to execute every 10 "tsteps" to overwrite the data in amid.txt
        {
            for (n = 0; n <= nmax; n++)
            {
                x = n*dx;
                fprintf(amid, "%f \t %f \n", x, rho[n]);
            }
        fclose(amid);   
        r++;        
        }
    }

    for (n = 0; n <= nmax; n++)
    {
        x = n*dx;
        fprintf(afinal, "%f \t %f \n", x, rho[n]);
    }
    fclose(afinal);   
return 0;
}

我的数组“amid”只写入一次,但我希望它写入信息,然后在更大的“tmax”循环中多次用新信息覆盖旧信息。有了这个,我想通过 gnuplot “随着时间的推移”绘制我的数据快照,这样我就可以观察我的微分方程的工作演变。

最佳答案

你是这个意思吗?:

for (tstep=1; tstep<=tmax; tstep++)
{
    rho[tstep] += -tstep;
    if(tstep == r)
    {
        rewind(amid);
        for (n = 0; n <= nmax; n++)
        {
            x = n*dx;
            fprintf(amid, "%f \t %f \n", x, rho[n]);
        }
        r += 10;
    }
}

// later....
close(amid);

顺便说一句:你为​​什么使用 rho[tstep] += -tstep; 而不是 rho[tstep] -= tstep; ...这似乎是一个有点难读,至少我不得不读两遍,你在那里做什么。

也许您的问题是,您过早关闭了该文件.. 还要注意您对代码的误导性缩进。

此外,您应该在这里提问。你的问题到底是什么?

关于c - 我需要我的方程式在循环的每 10 次迭代中覆盖文件中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18137866/

相关文章:

c - 如何正确分配内存缓冲区以使用 turbo c 在 dosbox 中应用双缓冲?

MySQL循环插入组合值

vba - 围绕我的选择案例创建一个循环

loops - 结果后的 Prolog 循环

c - 如何在c中制作字符串参数数组

c - 有谁知道为什么这个数组初始化语句不起作用?

使用有符号字符指针更改 int 数组的值

for-loop - 已声明但未在 for 循环中使用的变量

c - i ["string"] 如何用作条件语句?

java - java 中的内容根据 boolean 值进行更改