将For循环更改为Do While语句?

时间:2018-05-17 14:05:48

标签: vb.net console-application

Module Module1 
   Sub Main() 
      For value As Integer = 9 To 0 'Step 1'
         System.Console.WriteLine(value) 
      Next 
   End Sub 
End Module 

这应该是简单的想象,如何轻松地从“For循环”变为“Do While”声明?

2 个答案:

答案 0 :(得分:1)

您可以改为使用以下Do While循环:

Dim value As Integer = 9

Do While value <= 9 And value >= 0
    Console.WriteLine(value)
    value -= 1 'this count from 9 to 0
Loop

但是你的For并没有这样做。目前你For循环没有输出任何值。看起来你设置了错误的步骤:

For value As Integer = 9 To 0 Step -1
    Console.WriteLine(value) 'this count from 9 to 0
Next     

Do While循环解决方案从0到9计数:

Dim value As Integer = 0

Do While value <= 9 And value >= 0
    Console.WriteLine(value)
    value += 1 'this count from 0 to 9
Loop

For循环解决方案从0到9计数:

For value As Integer = 0 To 9 Step 1
    Console.WriteLine(value) 'this count from 0 to 9
Next

答案 1 :(得分:0)

这将永远不会进入循环,因为起始值高于结束,并且步骤不是负数。看这里: https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/for-next-statement#technical-implementation  要将其转换为Do-While,您必须首先检查开始和结束条件是否有效,否则它将陷入无限循环。