我不明白为什么我的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 SubResult: 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 5Each 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.
更多推荐
发布评论