需要帮助了解我的for循环如何工作

时间:2011-09-14 11:59:48

标签: c

#include<stdio.h>

int main(){
    int i;
    clrscr();
    for(i=0,i++,i<=5;i++,i<=2;i=0,i<=5,i+=3){
         printf("%d ",i);
    }
    return 0;
}

该程序的输出为2.请详细说明逻辑

5 个答案:

答案 0 :(得分:8)

此循环相当于:

i = 0;
i++;
i <= 5;

i++;
while (i <= 2)
{
    printf("%d ", i);

    i = 0;
    i <= 5;
    i += 3;

    i++;
}

我猜你之前可能没有遇到的部分是逗号运算符。用逗号分隔的表达式序列依次进行评估,“return”值是最终表达式的值。 e.g:

x = (y + 3, ++y, y + 5);

大致相当于:

y + 3;
++y;
x = y + 5;

答案 1 :(得分:2)

i=0,i++,i<=5;对应初始化。我变成了1  i++,i<=2;对应于测试条件。我变为2并且其值被打印  i=0,i<=5,i+=3;对应于增量条件,其中i的值变为5,这使测试条件失败,因此循环在此结束。

答案 2 :(得分:1)

初始化:i ++ //所以i = 1

条件:i ++ //所以i = 2且i&lt; = 2为真

打印2

增量i + = 3 //所以i = 5条件为假。走出循环

答案 3 :(得分:1)

好吧,它可能会让首发者感到困惑,但让我以更清洁的方式解释它,然后只是片段

让我将我的解决方案分为3部分:1)初始化2)条件3)增量为3个for循环

1st part 
i=0,i++,i<=5
i is assigned 0 
i++ increments to 1 
i<=5 \\ this code has no effect as it is used in assinging part of for loop
          it should be used only in condtions. so value of i is 1 
i<=5 \\ doesnt make any sense it keeps i value as it is

2nd part
i++,i<=2
i++ \\ i value is 2
i<=2 \\ these code has effect as it is in conditional part of for loop
  so now it checks the condition i<=2 and i value is 2 So condition becomes true
and enters into loop and prints the i value as 2

3rd part
i=0,i<=5;i+=3
i=0 assigns i = 0
i<=5 \\ as i told you, code has no effect so i still holding zero value in it
i+=3 implies i=i+3 (right hand operators)
as i value is zero it becomes i = 0+3 now i value is 3

goes to the condition part again
i++ \\ now i has four in it
i<=2 \\ fails as i value is 4 so loop exits

请记住并阅读有关逗号运算符和右手运算符的更多信息。

x=4
x=(x+2,++x,x-4,++x,x+5) 
x value is 11 now guess it why?

首先执行x + 2获得6但是忽略因为你没有提到存储值的变量,++ x使它成为5,因为它是增量或你不需要任何分配甚至x-4值被忽略而++ x使x为6,x + 5给出11,因为它结束时该值存储在x

我想我已经为你清楚明了了谢谢 再也不要怀疑了!

答案 4 :(得分:0)

加入@Oli Charlesworth的回答:

  1. 在进入循环之前,您需要增加i两次。
  2. 输入循环后,打印数字2。
    • 您从未评估过其他条件。
  3. 最后,你增加i,这使得它成为3并且循环在下一次迭代时停止(其中i设置为3,因此i现在大于2),程序退出。