C语言 我需要我的方程每循环 10 次迭代覆盖文件中的数据


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;......这似乎有点难读,至少我不得不读两遍,你在那里做什么。

也许你的问题是,你过早地关闭了那个文件......还要注意你的代码的误导性缩进。

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

尝试:

   if (tstep%10 == 0)
   //I want this if statement to execute every 10 "tsteps" to
   // overwrite the data in amid.txt

这是模组运算符。 它将 tstep 除以 10 并返回余数。 如果余数为零,则执行 for 循环。

此外,如果您的十步中需要一个"相位",那么tstep%10 == 2或 1、3,最多 9 步,那么您仍将每十步执行一次循环,仅相对于外循环进行偏移。

最新更新