循环只遍历一半的元素

Loop iterating only through half of the elements

这是我的代码。我的问题是,为什么它只打印 5 个数字?为什么它不能像预期的那样打印 10?

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

   int main(){

   int r, col;

   srand((unsigned)time(NULL));

   for (col=1; col<=10; col++){

   r = rand() % 11;
   printf("%d\n", r);
   col++;

   }
  return 0;
  }

因为,您正在执行 col++ 两次 ,一次在循环体中,一次在 post-循环语句中。

for (col=1; col<=10; col++)   //...................(i)
                    ^^^^^^^

r = rand() % 11;
printf("%d\n", r);
col++;                       //.....................(ii)
^^^^^

因此,对于单次迭代,col 增加 两倍 ,迭代次数减半。

删除其中一个语句。

你犯了一个错误 - 你不需要写两次 col++!!

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

int main(){

    int r, col;

    srand((unsigned)time(NULL));

    for (col=1; col<=10; col++){

        r = rand() % 11;
        printf("%d\n", r);
    }

    return 0;
}

双列++。 "for" 循环语句包括三个表达式。 First 在开始时被调用一次。通常用于计数器初始化。 其次是循环继续条件检查。在每次迭代之前调用。如果表达式的结果为假循环将被停止。 第三部分在每次迭代后调用。通常用于计数器增量。

如果您在 "for" 中使用了 col++ 并希望 "col" 每次迭代都递增 1,则您不会在循环体中执行 col++。

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

   int main(){

   int r, col;

   srand((unsigned)time(NULL));

   for (col=1; col<=10; col++){

   r = rand() % 11;
   printf("%d\n", r);
   //col++;

   }
  return 0;
  }