此for循环如何工作?

时间:2019-07-28 11:46:08

标签: c loops

我是C编程新手。我遇到了for循环示例。 我不了解循环的某些部分。输出是8。直到4为止,我都不知道b是怎么回事。这是我的代码。

int a = 4;
int b = 2;
int result = 0;

for(int count = 0; count != b; count++) {
    result = result + a;
}

printf("a times b is %i\n", result);

return 0;

5 个答案:

答案 0 :(得分:1)

有时候,最简单的方法是让程序进行自我解释:

#include <stdio.h>
#include <stdlib.h>

int main(void){
    int a = 4;
    int b = 2;
    int result = 0;

    for(int count = 0; count != b; count++) {
        printf("a = %3d, b = %3d, count = %3d, result = %3d\n", a, b, count, result);
        result = result + a;
        printf("a = %3d, b = %3d, count = %3d, result = %3d\n", a, b, count, result);
    }
    printf("a = %3d, b = %3d\n", a, b);

    printf("a times b is %i\n", result);

    return 0;
}

输出

a =   4, b =   2, count =   0, result =   0
a =   4, b =   2, count =   0, result =   4
a =   4, b =   2, count =   1, result =   4
a =   4, b =   2, count =   1, result =   8
a =   4, b =   2
a times b is 8

如您所见,b不变。 count等于count时,b会发生变化并退出循环。

答案 1 :(得分:0)

变量b不递增,变量count0开始并在for loop中递增。当count变量变为2时,循环结束。因此,循环运行两次(计数0和计数1),结果为4 + 4 = 8

答案 2 :(得分:0)

首先,count = 0b = 2不同,因此循环开始。这样,循环的第一次迭代就会得出结果,

result = 0 + 4

由于循环结束,count变量应继续count++,这意味着count = count + 1。因此,count = 0 + 1 = 1的价值与b = 2不再相同。

再次进入循环,

result = 4  + 4 # where the first number came from the result of first loop

现在,count++生成的count = 2现在与b = 2的值相同。然后,循环条件不匹配count != 2,不再循环并显示值result = 8

答案 3 :(得分:0)

它将执行2次

count = 0 ==> result = 0 + 4

并计数= 1 ==> result = 4 + 4 ==> result = 8

当计数达到2时2!= 2部分将为假,我们将退出for循环

答案 4 :(得分:0)

该循环只运行两次,我们可以像这样干循环: 变量的初始值:-> a = 4,b = 2,计数= 0,结果= 0

loop first run -> 
count = 0
count != 2 -> that is ->  0 != 2  => true
result = result + a   ->  0 + 4  = 4

second run ->
count = 1 
count != b -> that is ->  1 != 2  => true
result = result + a   ->  4 + 4 = 8

third run ->
count = 2
count != b -> that is ->  2 != 2 => false 
stop loop. 
And the final resultent values are as follow: a= 4, b= 2 , count = 2 and result = 8