如何编写嵌套的 for 循环
How to write a nested for-loop
>我正在运行一个程序,该程序可以预示常微分方程的欧拉近似。选择的步长越小,近似值越准确。我可以使用以下代码让它适用于设定的步长:
#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 );
}
}
希望这有帮助。
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么我的for循环不能正确获取argv
- 在基于范围的for循环中使用结构化绑定声明
- 通过for循环使用用户输入填充列表
- 使用for循环检查数组中的重复项
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 正在使用for循环创建QScatterSerie
- Python中的for循环与C++有何不同
- 在更改for循环的第三部分后,未使用for循环结果
- 在 for 循环中查找问题时遇到困难
- 嵌套for循环C++的问题(初学者)
- 如何用for循环在c++中生成单词三角形
- 如何在for循环中包含两个索引值的测试条件
- 带有多个独立参数的C++For循环
- 为什么我的程序在for循环中k=0时返回垃圾值
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- C++-For循环未执行
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- C++ 无法在字符数组中使用 for 循环打印字母模式