c - 2个变量的for循环

标签 c for-loop

我最近开始学习 C,我觉得这是一个不太聪明的问题,但我想知道你是否可以取 2 个变量,初始化它们,评估它们的条件并在 1 个 for 循环中递增它们

假设我有 2 个整数:a 和 b,我想初始化它们并递增它们。

for(a=1, b= 1; a < 10 , b < 6; a++, b++)
{
    printf("a= %d\n", a);
    printf("/tb= %d\n", b);
}

有没有这行不通的原因? 还是我做错了?

我看过this question但在其中他/她只想增加 2 个变量,而我想为我的两个变量应用所有内容

最佳答案

Is there a reason this doesnt work? or am I just doing it wrong?

它确实有效,但不是您预期的那样:

a < 10 , b < 6评估 a < 10然后 b < 6但这是 b < 6 的结果被退回。所以你的循环只会转到 5。

Comma oparator (wikipedia)

让我解释一下 for 循环的工作原理:

您有三个“段”,它们都是可选的:

  • initialisation这部分在循环开始之前运行一次
  • condition如果此 condition 在每次迭代之前 评估此部分计算结果为 false 循环退出。
  • increment每次 迭代后执行。
for ( initialisation ; condition ; increment ) {
     /* body of the for loop */
}

您可以使用 while 实现相同的语义循环:

initialisation;

while (condition) {
    /* body of the for loop */
    increment;
}

例如:

for (;1;)永远不会退出和for (;0;)永远不会运行。

要实现所需的行为,您可以执行以下操作:

//1-9, and values of "b" which are 1-5
int a, b;

for (a = 1, b = 1; a <= 9; ++a, (b <= 4 ? ++b : 0)) {
    printf("a: %d\n", a);
    printf("b: %d\n", b);

    printf("\n");
}

但是您最好在 for 循环的内部执行此操作:

int a, b;

// This reads much better
for (a = 1, b = 1; a <= 9; ++a) {
    printf("a: %d\n", a);
    printf("b: %d\n", b);

    printf("\n");

    if (b <= 4) {
        ++b;
    }
}

关于c - 2个变量的for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49154483/

相关文章:

C:for 循环与 scanf 的行为真的很奇怪

algorithm - 这个嵌套for循环算法的时间复杂度?

c - 解码这些 Valgrind 调试器内存错误在我的代码中意味着什么

c - 在图形中查找线性

c - Matlab 在 MEX 函数中崩溃

c - 如何正确初始化Raspberry?

c++ - 文件夹大小 linux

javascript - 将 for 循环变成 lodash _.forEach

bash - md5 目录树中的所有文件

python - 我如何将变量 names_and_ranks 分配给列表,每个元素等于城市名称及其对应的排名?