简体   繁体   English

C#中ForLoop的一个简单问题

[英]a simple problem with ForLoop in C#

I want it to run three times but it actually never runs the loop and gets out. 我希望它运行三次,但它实际上从未运行循环并退出。 In VB 6.0 I could do that with a similar structure but how can I achieve the same thing with C# for loop? 在VB 6.0中,我可以用类似的结构来做到这一点但是如何用C#for循环实现相同的功能呢? I want to to count down but it is not ALWAYS the case, sometimes I am passing "1" and sometimes "-1" for the step , when passed with "-1" it does not work 我想要倒数,但事实并非如此,有时我传递的是“1”,有时是“-1”,当传递“-1”时,它不起作用

    for (int L = 3; L <= 1; L += -1)
    {
        MessageBox.Show("dfsdff");
    }

Yes because you have the second clause (the "keep going whilst this is true" clause) the wrong way around, try this: 是的,因为你有第二个条款(“继续这是真的”条款)错误的方法,试试这个:

 for (int L = 3; L >= 1; L--)
    {
        MessageBox.Show("dfsdff");
    }

Now it says "start at 3", "decrement" (--) whilst L is bigger than or equal to 1. 现在它说“从3开始”,“递减”( - ),而L大于或等于1。

It looks like your terminal condition of L <= 1 is what is throwing you off. 看起来您的终端条件L <= 1就是让你失望的原因。

You probably meant to reverse that and say L >= 1 . 你可能想要扭转它并说L >= 1 Otherwise when L is initialized to 3, and then the terminal is evaluated it would immediately return false saying that L is greater than 1, and therefore terminate your loop. 否则,当L初始化为3,然后终端被评估时,它会立即返回false,表示L大于1,因此终止循环。

the for loop can be written out as: for循环可写为:

for(variable L = 3; as long as L satisfies condition L <= 1; increment L by -1)

Your L will always be greater than 1, so the loop never gets executed. 你的L总是大于1,所以循环永远不会被执行。 The right way would be either: 正确的方法是:

for(int L = 0; L <= 2; L++)

or 要么

for(int L = 2; L >= 0; L--)

if you want to start with 1, just modify accordingly. 如果你想从1开始,只需相应修改。

try this: 尝试这个:

for (int L = 3; L >= 1; L--)
    {
        MessageBox.Show("dfsdff");
    }

That should count down for you, I've corrected it. 这应该倒数,我已经纠正了。 They are correct, it was an infinite loop. 它们是正确的,它是一个无限循环。 Here is another way to do it, that might make more brain sense. 这是另一种方法,可能会让大脑更有意义。

int L = 3
while( L > 0)
{
    MessageBox.Show("Your clever message);
    L--;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM