如何编写嵌套的 for 循环

How to write a nested for-loop

本文关键字:for 循环 嵌套 何编写      更新时间:2023-10-16

>我正在运行一个程序,该程序可以预示常微分方程的欧拉近似。选择的步长越小,近似值越准确。我可以使用以下代码让它适用于设定的步长:

#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";
}
}

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

希望这有帮助。