vb.net For 循环步骤 -1

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22678063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 17:13:36  来源:igfitidea点击:

For Loop Step -1

vb.netloops

提问by Iswanto San

I want to know why this loop doesn't show anything in VB.NET.

我想知道为什么这个循环在 VB.NET 中没有显示任何内容。

I think this code will create an infinite loop. But it doesn't show anything.

我认为这段代码将创建一个无限循环。但它没有显示任何东西。

Dim i as Integer
For i = 1 to 3 Step - 1
    MessageBox.Show(i)
Next

Is that loop different with this code (in java/c#) ?

该循环与此代码(在 java/c# 中)不同吗?

for(int i = 1;i <= 3;i--)
{
  // print i
}

回答by JamesH

http://msdn.microsoft.com/en-us/library/5z06z1kb.aspxWith a negative step size the loop only executes if counter >= end. So in this case with i = 1, that is less than the ending value so the loop doesn't execute at all.

http://msdn.microsoft.com/en-us/library/5z06z1kb.aspx对于负步长,循环仅在 counter >= end 时执行。因此,在 i = 1 的情况下,它小于结束值,因此循环根本不执行。

回答by Sam Axe

It doesn't show anything because you are running the counter backwards without reversing the start and end conditions.

它没有显示任何内容,因为您在不反转开始和结束条件的情况下向后运行计数器。

Think of the loop like this:

想想这样的循环:

Dim counter As Int32 = 1
Do
  If counter <= 1 Then
    Exit Do
  End If
  Console.WriteLine("The counter is at " & counter)
  counter +=1
Loop

Obviously this won't work properly. You need to reverse the start and end conditions:

显然这不会正常工作。您需要颠倒开始和结束条件:

For counter = 3 To 1 Step -1
  Console.WriteLine("counter: " & counter)
Next

回答by cf stands with Monica

For i = 1 to 3 Step - 1

It won't create an infinite loop. The loop will simply be skipped, because you can't get from 1 to 3 with a step value of -1.

它不会造成无限循环。循环将被简单地跳过,因为您无法使用 -1 的步长值从 1 到 3。

Is that loop different with this code (in java/c#) ?

该循环与此代码(在 java/c# 中)不同吗?

This loop will also end immediately, because the initial value (i = 1) meets the exit condition (i <= 3).

此循环也会立即结束,因为初始值 ( i = 1) 满足退出条件 ( i <= 3)。