开发者

Is there a way to use a nonlinear stepsize in a vb.net loop?

开发者 https://www.devze.com 2023-03-03 14:09 出处:网络
I would like to do the following c statement in vb. for(int i = 2^20; i > 0; i/=2) { printf(\"%d\\n\",i);

I would like to do the following c statement in vb.

for(int i = 2^20; i > 0; i/=2)
{
   printf("%d\n",i); 
}  

In vb would look similar to:

For i As Integer = 2^32 to 0 Step /2
   Console.Out.Writeline("{0}", i)
Next

Specifically, the variable where i is divided by 2 each iteration is not legal 开发者_如何学运维vb.

Is there a way to write this using a For statement that is allowed?


No, the FOR loop in VB is shorter but less flexible.

And the obvious work-around is of course a While loop.

' untested
Dim i As Integer = 2^30  ' 2^32 will overflow
While i >= 0
   Console.Writeline("{0}", i)
   i = i Div 2
End While


There are two typical approaches:

  1. Derive a formula to convert a linear (preferably integer-value) index into whatever values are needed for the loop, and then employ such a formula.
  2. Use a method to generate one or more "IEnumerable"s to return the proper values in sequence and then replace the "For" with a "For Each"

The former approach is the one I usually use; I believe LINQ includes some methods to facilitate the latter approach (something like Enumerable.Range) but I don't know the details.

0

精彩评论

暂无评论...
验证码 换一张
取 消