找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
首页论坛EAHub 外汇论坛
查看: 14|回复: 0

MQL4 语言入门之循环

[复制链接]

4万

主题

54

回帖

4万

积分

管理员

积分
45954
发表于 2026-8-22 08:48:00 | 显示全部楼层 |阅读模式
循环假设您决定要计算图表中所有条柱的最大价格的平均值。为此,您将各个元素轮流添加到一个变量,如下所示:double AveragePrice = 0.0;   AveragePrice += High[0];AveragePrice += High[1]; AveragePrice += High[2]; AveragePrice += High[3]; AveragePrice += High[4];   // ... and so onAveragePrice /= Bars;我只能告诉您一点:这种方法可行,但有些可笑。循环专门适用此类用途。注意,所有运算都是完全类似的,只有指数从 0 更改为变量 Bars-1 值。确定计数器并用其引用数组元素某种程度上来说就已经非常方便了。我们可以用循环来解决这个任务:double AveragePrice = 0.0;   for(int a = 0; a < Bars; a++){         AveragePrice += High[a];}我们看看各行:double AveragePrice = 0.0; // everything is clear// this is a cycle.or(int a = 0; a < Bars; a++)循环用关键字 for 开头。(还有其他类型的循环,例如while,但我们现在不讨论它们)。然后在引号中指明用分号隔开的计数器、循环计算条件、计数器增加运算。通常它以以下方式呈现:for(declaration of a counter; the cycle operation conditions;   counter changes)  {    // the source code, that will be repeated is in braces,  }让我们更近距离地了解循环声明的各个阶段。

计数声明int 类型用于此计数器。变量计数器的名称无关紧要。您应初始化主值,例如初始化为 0。

计数器计算条件:这很简单。在此处确定一个条件,如果它为 true,循环继续进行。否则,循环终止。例如在我们的示例中:a < Bars很明显,当变量计数器小于变量 Bars 时,循环将继续进行。假设变量 Bars=10,则在循环上每移动一次,变量增加 1,直至达到 10。之后,循环将停止。计数器更改:如果我们不更改计数器(在我们的示例中是增加它),将发生什么情况?循环将永不停止,因为条件永不会满足。为了更好地理解循环的意义,我编写了一段可执行循环的代码,并提供了注释:// the cycle:// double AveragePrice=0.0;//// for(int a=0;a>// {//   AveragePrice+=High[a];// }//// will be performed in this way://double AveragePrice=0.0;int a=0;AveragePrice+=High[a];a++;                    // now a=1, suppose Bars=3.                        // then the cycle goes on, because Bars > a AveragePrice+=High[a];a++;                   // a=2AveragePrice+=High[a];а++;                   // a=3// the conditions is not fulfilled any more, so the cycle // stops, because a=3 and Bars=3现在您应该了解循环的工作方式了。但还应该再了解一些细节。循环计算条件各有不同。如下例中所示:a>10    // the cycle works while a>10a!=10   // the cycle works while a is not equal to 10a==20   // while a is not equal to 20a>=2    // while a is more or equal to 2a<=30   // while a is less or equal to 30计数器可用不同的方式进行更改。例如,您不必每次都加 1。您可以这么做:a--     // the counter will each time decrease by 1 a += 2  // the counter will each time increase by 2此外,您可将计数器更改放到循环主体内。如下例中所示:for(int a=0; a<Bars;) {   AveragePrice+=High[a];      a++; // the counter changes inside the cycle body  }>也不必在循环中声明变量计数器。您可以换一种方式:int a = 0; for(;a < Bars;) {   AveragePrice += High[a];    a++; // the counter changes inside the cycle body }如果循环主体仅包含一个操作符,如下所示:

for(int a = 0; a < Bars; a++) {   AveragePrice += High[a]; }然后也不必使用发括号:for(int a = 0; a < Bars; a++)    AveragePrice += High[a];这就是目前为止有关循环的所有内容了。还有其他的循环类型,我们会在下一课中讨论。现在您应该知道何时使用循环并记住语法。尝试编写几个循环,以通过 MessageBox() 函数显示计数器值。尝试编写一个非连续循环,看看启动后会发生什么。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|EAHub外汇论坛

GMT+8, 2026-10-11 23:15 , Processed in 0.104413 second(s), 19 queries .

Powered by Discuz! X3.5

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表