0
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“随时间”绘制我的数据快照,这样我就可以观察我的微分方程的工作演变。

4

2 回答 2

1

你的意思是这样吗?:

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

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

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

于 2013-08-08T23:38:38.737 回答
1

尝试:

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

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

此外,如果在您的十个步骤中需要一个“阶段”,然后tstep%10 == 2或 1、3、最多 9 个,那么您仍将每十个步骤执行一次循环,仅相对于外部循环有一个偏移量。

于 2013-08-09T00:56:17.897 回答