简体   繁体   English

初学者C“ ==”始终计算为false

[英]beginner C “==” always evaluates to false

Just a beginner question. 只是一个初学者的问题。 I tried to find an answer to this but I couldn't. 我试图找到答案,但是没有。

Why 为什么

for (int i = 0;i==10;++i) {
/* body of the for loop */
}

Never executes the body of the for loop? 永远不要执行for循环的主体? but this one works? 但是这个有效吗?

for (int i = 0;i<=10;++i) {
/* body of the for loop */
}

The (i==0) should be a boolean expression evaluating to false if i==0, right? (i == 0)应该是一个布尔表达式,如果i == 0,则计算为false,对吗? This perfectly works if I put that expression in an if statement like 如果我将表达式放在类似if的语句中,这将非常有效

for(int i=10;;++i) {
if (i==10) break;
}

Thanks! 谢谢!

C ++ 101:中间条件必须为true,循环才能继续。

A for loop basically means to continue as long as the middle condition is true. for循环基本上意味着只要中间条件为真就继续。

So the loop, in this case will only continue when i==10. 因此,在这种情况下,循环只会在i == 10时继续。 Which it isn't therefore it stops. 因此不是它停止了。

Because the condition in your first loop says only to increment when i is equal to to 10. You set i to 0, so it will never increment because it has no way of getting there. 因为您的第一个循环中的条件仅在i等于10时才说增加。将i设置为0,所以它永远不会递增,因为它无法到达那里。

The second one works because you say i is equal to 0, and while i is less than or equal to 10, it is incremented by 1. 0 is less than 10, but not equal to it. 第二个之所以起作用,是因为您说i等于0,并且当i小于或等于10时,它以1递增。0小于10,但不等于10。

for (int i = 0; <condition>;++i) {
/* body of the for loop */
}

The key to understanding this is that the body executes every time the condition evaluates to TRUE. 理解这一点的关键是,每当条件评估为TRUE时,身体就会执行。 In your example, it evaluates to FALSE first time itself, and hence nothing executes. 在您的示例中,它本身第一次评估为FALSE,因此没有任何执行。

In your second example, condition is omitted. 在第二个示例中, 条件被省略。 Which means the body executes forever, until you break out of it. 这意味着身体永远执行,直到您脱离它。 Which you do when i == 10. Hence the body executes 10 times. 当i == 10时执行该操作。因此,身体执行了10次。

for(;true;)
{
//this is infinite loop
}

为了进入循环,条件应该为true,在您的情况下,i == 10返回false,因此不会进入循环。

        for (int i = 0;i==10;++i) {
         /* body of the for loop */
        }

for this code i=0 initially, when condition is checked (i==10) it results in false so loop will not iterate. 对于此代码,i = 0最初,当检查条件(i == 10)时,结果为false,因此循环不会迭代。

Check carefully for what values of i you want to run the loop. 仔细检查要运行循环的i的值。

for example your loop may be 例如你的循环可能是

     for (int i = 0;i<=10;++i) {
       /* body of the for loop */
      }

the body of loop will iterate from 0 to 10 including both. 循环的主体将从0迭代到10,包括两者。

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

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