基本:为什么结果与此 For 循环中的值不同?

Basic: Why is the result different than the value in this For loop?

    For num = 100 To 5 Step -5
        TextWindow.WriteLine(num)
    EndFor

此代码在控制台中显示的最终值为 5。但是,在 For 循环外部使用 'num' 变量时,'num' 的值会导致 0。为什么当我指定停止在 5 时,num 的值不是 5 吗?这里发生的计算机逻辑是什么?

    For num = 100 To 5 Step -5
        TextWindow.WriteLine(num)
    EndFor
    TextWindow.WriteLine(num)

使用上面的代码片段,'num' 在控制台中的最终值显示为 0。

提前感谢大家花时间帮助我解决这个初学者问题!

Why is the value of num not 5 when I specify to stop at 5?

准确地说,你指定5是最后一个要处理的值(即当num为5时,循环体仍然运行)。在迭代结束时,计数器 (num) 递减,下一次迭代开始。 num 现在为零(小于 5)并且循环退出,因为现在满足其停止条件。这就是您获得该输出的方式。

这个代码

For num = 100 To 5 Step -5
    ' Body
EndFor

相同
num = 100

While num >= 5
    ' Body

    num = num - 5
End While

所以当num得到0时循环结束。

(如果我提供的代码有什么错误,我用心写了)