开发者

division incrementor in a for loop?

开发者 https://www.devze.com 2023-03-18 01:56 出处:网络
Basic question here, just got curious about coding a simp开发者_StackOverflow中文版le formula out, and wanted to know if it\'s possible to use a division operator for the increment in a c# for loop?

Basic question here, just got curious about coding a simp开发者_StackOverflow中文版le formula out, and wanted to know if it's possible to use a division operator for the increment in a c# for loop?

Using int X, would like to divide X repeatedly by some number Y until X <= some number Z.

for ( x = 0; x <= Z; X/Y) ? // Here, I throw an error at X/Y, also with (X/Y).


The last segment in for loop is usually meant for changing the loop variable (usually incrementing or decrementing). So, x++ (which is x = x + 1) increments x. x/y does not change x (or y, and is not a valid C# statement). you could do x /= y which would compile.


I think you mean x = x / y. x/y does nothing useful on it's own and, while it's at least valid syntax in C and C++, I'm not sure C# will not allow it.

But you should keep in mind that you have your condition "bass-ackward" (a) :-) This condition must be satisfied for the loop to continue, not to terminate.

So, if you mean (as you state) "... until X <= some number Z", the loop should be:

for (x = 0; x > Z; x = x / Y)

In any case, since x starts at zero, and zero divided by anything (except zero) is still zero, the value of x will never change. I suspect you meant to start x at some larger value since you're reducing it with the division operator and you want to terminate when it drops below a certain value.


(a) To be honest, I'm not sure why this phrase is so popular. It's a corruption of the obvious Spoonerism meaning things are the wrong way around but, as far as my limited knowledge of anatomy goes, I'm pretty certain the a** is supposed to be backwards :-)


/= is the divisional incremental operator.

x /= 2;

is functionally equivalent to

x = x / 2;

should be fine to use it.

// changing x = 1 in example code, as per discussion below this comment
for (x = 1;x <= z;x /= y) 
{
//whatever
}


on increment section, it should be statement. like, x=x/y


Sure, but in addition to what others have pointed out about actually reassigning x:

  • If x starts at 0, it will never change
  • The condition is a continue condition ("while"), not a termination condition ("until")

So you would end up with:

for( var x = max_x; x > min_x; x /= y )
0

精彩评论

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