【问题标题】:How to write a nested for-loop如何编写嵌套的for循环
【发布时间】:2018-09-29 21:23:58
【问题描述】:

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

#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 的欧拉近似值,该近似值对应于 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";

     }

 }

【问题讨论】:

  • 为什么n 需要硬编码?想象一下你可以用for (int n = 20; n &lt; 30; ++n){ ...做些什么
  • 如果你有一个装东西的盒子,盒子本身并不关心里面装的是什么。它可能是另一个盒子。简单地说,for 循环中的 for 循环就是 for 循环中的 for 循环。你到底有什么不清楚的地方?将您的单个 int n 替换为在您希望的值范围内迭代 n 的 for 循环,然后在其中您拥有现有代码。对此,您的具体问题是什么?
  • 不需要硬编码!我正在尝试运行它,所以它不是硬编码的。但是,当我用“for (int n = 20; n
  • 所以我有这样的东西,但它对我不起作用,我得到一个无用的输出! for (int n=20;n&lt;40;n++) { double h = (t1-t)/n; for (int i=0;i&lt;n;i++) { x += h+f(x,t); t += h; } cout &lt;&lt; h &lt;&lt; " " &lt;&lt; x &lt;&lt; "\n"; } 这是我在 for 循环中的 for 循环尝试,但显然我做错了什么。
  • 我怀疑这种螺旋式失控是因为 xtt1 被先前的循环运行改变了。我的建议:将这些变量和欧拉的方法逻辑放入像double eulersMethod(double t, double t1, int n)这样的函数中

标签: c++ loops for-loop approximation


【解决方案1】:

如果我理解正确,您希望在主函数中针对不同的 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 );
    }
}

希望这会有所帮助。

【讨论】:

  • 这正是我想要做的!非常感谢你的回复。如果我的问题不够清晰/简洁,我深表歉意,我在这里发布的内容不多。
  • 很高兴能帮上忙!欢迎来到 Stack Overflow。如果这是您正在寻找的答案,您能否将其标记为已接受?谢谢。
猜你喜欢
  • 1970-01-01
  • 2014-03-20
  • 2014-11-05
  • 1970-01-01
  • 2016-01-21
  • 1970-01-01
  • 1970-01-01
  • 2022-06-15
  • 2021-03-13
相关资源
最近更新 更多