如何编写嵌套的for循环

时间:2018-09-29 21:23:58

标签: c++ loops for-loop approximation

我正在运行一个程序,该程序执行一个常微分方程的欧拉近似。选择的步长越小,近似值越准确。我可以使用以下代码使其在设定的步长下工作:

#include <iostream>
using std::cout;

double f (double x, double t)
 {
     return t*x*x-t;
 }

 int main()
 {
     double x=0.0,t=0.0,t1=2.0;
     int n=20;
     double h = (t1-t) / double(n);

 // ----- EULERS METHOD

     for (int i=0; i<n; i++)
     {
         x += h*f(x,t);
         t += h;
     }

     cout << h << " " << x << "\n";

 }

因此,此代码对n = 20进行Eulers逼近,它对应于0.1的步长,并输出步长以及x(2)的逼近。我想让高层知道如何循环执行此代码(对于n的不同值),以便输出该代码,然后输出步距越来越小且具有近似值的代码。 即这样的输出:

0.1   -0.972125
0.01  -0.964762
0.001 -0.9641

所以我在for循环中尝试了for循环,但是它给了我一个极端值的怪异输出。

#include <iostream>
using std::cout;

double f (double x, double t)
 {
     return t*x*x-t;
 }

int main()
 {
     double x=0.0,t=0.0,t1=2.0;

     for (int n=20;n<40;n++)
     {
         double h = (t1-t)/n;
         for (int i=0;i<n;i++)
         {
             x += h*f(x,t);
             t += h;
         }
         cout << h << " " << x << "\n";

     }

 }

1 个答案:

答案 0 :(得分:0)

如果我理解正确,那么您想针对不同的n值在主函数中执行第一段代码。然后,您的问题出在变量x,t和t1上,这些变量在循环之前设置一次,并且永不复位。您希望它们位于外循环中:

#include <iostream>

using std::cout;

double f( double x, double t )
{
    return t * x * x - t;
}

int main()
{
    for ( int n = 20; n < 40; n++ )
    {
        double x = 0.0, t = 0.0, t1 = 2.0;
        double h = ( t1 - t ) / n;
        for ( int i = 0; i < n; i++ )
        {
            x += h * f( x, t );
            t += h;
        }
        cout << h << " " << x << "\n";
    }
}

为此使用函数,使其更清晰:

#include <iostream>

using std::cout;

double f( double x, double t )
{
    return t * x * x - t;
}

void eulers( const int n )
{
    double x = 0.0, t = 0.0, t1 = 2.0;
    double h = ( t1 - t ) / n;
    for ( int i = 0; i < n; i++ )
    {       
        x += h * f( x, t ); 
        t += h; 
    }       
    cout << h << " " << x << "\n";
}

int main()
{
    for ( int n = 20; n < 40; n++ )
    {
        eulers( n );
    }
}

希望这会有所帮助。

相关问题