对于Visual Basic中的循环结果错误的循环次数(For Loop in Visual Basic results wrong number of loops)

编程入门 行业动态 更新时间:2024-10-26 21:35:07
对于Visual Basic中的循环结果错误的循环次数(For Loop in Visual Basic results wrong number of loops)

我不明白为什么我的x值为6,而我认为它应该是5。

Sub Main() Dim x = 0 For x = 1 To 5 Next Console.WriteLine(x) Console.ReadLine() End Sub

结果: 6

I don't understand why I get x with a value of 6 while I think it should be 5.

Sub Main() Dim x = 0 For x = 1 To 5 Next Console.WriteLine(x) Console.ReadLine() End Sub

Result: 6

最满意答案

x等于6的原因是由于循环的性质。 你没有把代码放在循环体内。 如果你打印你的代码,你会看到

1 2 3 4 5

每次到达下一个时, x递增。 第五次循环时, x递增到6.在大多数情况下,最好不要在循环外部使用循环变量。 使用C风格循环我的意思是更清楚

for (int i=0; i<=5; i++){}

循环运行直到条件i <= 5不成立。 由于每次通过循环i都增加1,当i等于6时,首先发生。我在这里使用了变量i ,因为i是一个比x更常见的循环变量名称。

The reason that x equals 6 is because of the nature of a loop. You put no code inside the body of the loop. If you printed your code there you would see

1 2 3 4 5

Each time Next is reached, x is incremented. The fifth time you go through the loop, x is incremented to 6. In most cases it's best to not use loop variables outside of their loop. Using a C style loop what I mean is a bit more clear

for (int i=0; i<=5; i++){}

The loop runs until the condition i <= 5 is not true. Since each time through the loop i is increased by 1 this occurs first when i equals 6. I used the variable i here because i is a much more common loop variable name to see than x.

更多推荐

本文发布于:2023-07-31 00:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340396.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:次数   错误   Visual   Basic   Loop

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!