对于 c 中的重复语句

for Repetition Statement in c

执行for语句时,计数器变量的值必须加一,因为我使用了预自增运算符。

#include <stdio.h>
int main (void)
{
    unsigned int counter ;
    for ( counter = 1; counter <= 10; ++counter /*here is problem*/) {
        printf( "%u\n", counter );
    }
}

问题 -

When the program is executed, the value of counter variable initially is 1 instead of 2.

for 循环中

for(first statement; second statement; third statement){//...}; 

通常用于 updation 的第三条语句在每次迭代结束时执行,因此您的变量 counter 将是 1第一次迭代并在第一次迭代结束时变为 2


如果你想让你的 counter 变量在迭代开始时递增,那么尝试在 for 循环的第二个语句中使用它 ++counter 这样:

for ( counter = 1; ++counter <= 10;)

原因:

因为,for 循环是预测试循环,在每次迭代开始时检查通常是第二条语句的条件。所以现在你的 counter 在每次迭代开始时递增

for语句执行时then

第一次没有检查 for 循环的第三条语句是否使用递增运算符或给 for 循环的条件,但是

当循环开始迭代时,如果您在 for 循环的第三条语句中使用任何递增或递减运算符,那么它会起作用,如果您在 for 循环的第三条语句中使用任何条件,那么您的程序将永远不会结束,从而导致无限循环.

如果要从2开始计数,应该在for循环中初始化count为

for ( counter = 2; counter <= 10; counter++) {
    printf( "%u\n", counter );
}

C 遵循 for loops 的以下语法:

for ( init; condition; increment ) {
   statement(s);
}

此处的初始化部分是您进行初始化的地方。